Hello how to remove brackets from API response with vue JS - javascript

im trying to remove brackets and 2 letters from an API response that i got with axios, i show the data with vue js but they are showing like this :
["188 cm"]
What will be the best way to only show 188 by removing Brackets and cm [" cm"] ?
Thank you

"Removing the brackets" is the straightforward part. What you have is simply an array with one element, so you can access the first element in that array. (Assuming of course there's always at least one element, if it's possible for the array to be empty then you will want to put in some range checking before trying to access the element.)
The second part, "removing the ' cm' part", can be done in a couple of different ways. You can split the string on the space character and take the first part of the result, you can simply replace " cm" with "", or if what you want is the actual number and the string always starts with that number then parseInt will ignore everything after that number by default.
For example:
let theArray = ["188 cm"];
let theString = theArray[0];
let theNumber = parseInt(theString);
console.log(theNumber);

Related

Shifting characters in a string

I am trying to develop a function inside an external Javascript file that I can later call/use inside an HTML file. I need this function to take a string and shift the individual characters over one, I.E the string "ABCDE" would become "BCDEA" after going through the function. But instead of that specific string, I would like to be able to use a string variable named "key", since the string that needs to be shifted can be whatever the user enters for it. I am completely lost and unsure of what to do so any help would be appreciated.
The only thing I can think of possibly doing is subtracting the index of the first character in the string by one, so it would be -1 resulting in the code thinking that it is at the back of the string since the last character is assigned -1 but I don't know if it will even work, or how to set it up if it did.
You can shift a string using the following function that uses simple substring() manipulation which is a function you can call on all strings:
function shiftString(str, shift) {
return str.substring(shift) + str.substring(0, shift);
}
Running for instance shiftString("ABCDE", 2) will result in "CDEAB", since:
str.substring(2) == "CDE" (take all characters from the second index onward; strings are zero-indexed)
str.substring(0, 2) == "AB" (take the 0-th index until the second index)

Match between simple delimiters, but not delimiters themselves

I was looking at JSON data that was just in a text file. I don't want to do anything aside from just use regex to get the values in between quotes. I'm just using this as a way to help practice regex and got to this point that seems like it should be simple, but it turns out it's not (at least to me and a few other people at the office). I've matched complicated urls with ease in regex so I'm not completely new to regex. This just seems like a weird case for me.
I've tried:
/(?:")(.*?)(?:")/
/"(.*?)"/
and several others but these got me the closest.
Basically we can forget that it's JSON and just say I want to match the words value and stuff out of "value" and "stuff". Everything I try includes the quotes, so I'd have to clean the strings afterwards of the delimiters or else the string is literally "value" with the quotes.
Any help would be much appreciated, whether this is simple or complicated, I'd love to know! Thanks
Update: Alright so I think I'll go with (?<=")(.*?)(?=") and read things by line without the global setting on so I just get the first match on each line. In my code I was just plopping in a huge string into a var in the code instead of actually opening a file with ajax/filereader or having a form setup to input data. I think I'll mark this as solved, much appreciated!
You have two choices to solve this problem:
Use capturing groups
You can match the delimiters and use capturing groups to get the text within. In this case your two regexes will work, but you need to use access capturing group 1 to get the results (demo). See How do you access the matched groups in a JavaScript regular expression? for how to do that.
Use zero-width assertions
You can use zero-width assertions to match only the text within, require delimiters around them without actually matching them (demo):
(?<=")(.*?)(?=")
but now since I'm not consuming the quotes it'll find instances between each quote, not just between pairs of quotes: e.g., a"b"c" would find b and c.
As for getting just the first match, I think that'll happen by default in JavaScript. You'd have to ask for repeated matching before you see the subsequent ones. So if you process your file one line at a time, you should get what you want.
get the values in between quotes
One thing to keep in mind is that valid JSON accepts escaped quotes inside the quoted values. Therefore, the RegEx should take this into account when capturing the groups which is done with the “unrolling-the-loop” pattern.
var pattern = /"[^"\\]*(?:\\.[^"\\]*)*"/g;
var data = {
"value": "This is \"stuff\".",
"empty": "",
"null": null,
"number": 50
};
var dataString = JSON.stringify(data);
console.log(dataString);
var matched = dataString.match(pattern);
matched.map(item => console.log(JSON.parse(item)));

Javascript replacing single quote with empty string

This is an odd one! I kind of want to say the reason my replace function isn't working correctly is because of the font. I've never seen this issue before, and I wonder if I'm overlooking something!?
I have the following variable set to a static text with '.
var lastName = "O'Donnell";
In my browser, console.log(lastName) outputs: O’Donnell. Instead of O'Donnell. Therefore, the following replace method isn't working.
Screenshot:
return lastName.replace(/'/g, '')
What am I doing wrong?
The character you're trying to replace isn't the same as the one in the name.
Best to remove all non alpha numeric characters instead, to cater for names such as:
O'Neill
St. Mary's
Try:
lastName.replace(/\W/g, '')

Matching a JS string with regex

I have a long xml raw message that is being stored in a string format. A sample is as below.
<tag1>val</tag><tag2>val</tag2><tagSomeNameXYZ/>
I'm looking to search this string and find out if it contains an empty html tag such as <tagSomeNameXYZ/>. This thing is, the value of SomeName can change depending on context. I've tried using Str.match(/tagSomeNameXYZ/g) and Str.match(/<tag.*.XYZ\/>/g) to find out if it contains exactly that string, but am able to get it return anything. I'm having trouble in writing a reg ex that matches something like <tag*XYZ/>, where * is going to be SomeName (which I'm not interested in)
Tl;dr : How do I filter out <tagSomeNameXYZ/> from the string. Format being : <constant variableName constant/>
Example patterns that it should match:
<tagGetIndexXYZ/>
<tagGetAllIndexXYZ/>
<tagGetFooterXYZ/>
The issue you have with Str.match(/<tag.*.XYZ\/>/g) is the .* takes everything it sees and does not stop at the XYZ as you wish. So you need to find a way to stop (e.g. the [^/]* means keep taking until you find a /) and then work back from there (the slice).
Does this help
testString = "<tagGetIndexXYZ/>"
res = testString.match(/<tag([^/]*)\/\>/)[1].slice(0,-3)
console.log(res)

How can I split text on commas not within double quotes, while keeping the quotes?

So I'm trying to split a string in javacript, something that looks like this:
"foo","super,foo"
Now, if I use .split(",") it will turn the string into an array containing [0]"foo" [1]"super [2]foo"
however, I only want to split a comma that is between quotes, and if I use .split('","'), it will turn into [0]"foo [1]super,foo"
Is there a way I can split an element expressing delimiters, but have it keep certain delimiters WITHOUT having to write code to concatenate a value back onto the string?
EDIT:
I'm looking to get [0]"foo",[1]"super,foo" as my result. Essentially, the way I need to edit certain data, I need what is in [0] to never get changed, but the contents of [1] will get changed depending on what it contains. It will get concatenated back to look like "foo", "I WAS CHANGED" or it will indeed stay the same if the contents of [1] where not something that required a change
Try this:
'"foo","super,foo"'.replace('","', '"",""').split('","');
For the sake of discussion and benefit of everyone finding this page is search of help, here is a more flexible solution:
var text = '"foo","super,foo"';
console.log(text.match(/"[^"]+"/g));
outputs
['"foo"', '"super,foo"']
This works by passing the 'g' (global) flag to the RegExp instance causing match to return an array of all occurrences of /"[^"]"/ which catches "foo,bar", "foo", and even "['foo', 'bar']" ("["foo", "bar"]" returns [""["", "", "", ""]""].)

Categories

Resources