This question already has answers here:
How to convert a string of numbers to an array of numbers?
(18 answers)
Closed 3 years ago.
I m getting result as '2,3,7' as result from database, now I want to remove ' (single quote) from the string and get output as 2,3,7
My intention is to use this values as array like [2,3,7]. But due to it is string it is storing like ['2,3,7'].
I have tried to convert it to an integer using parseInt but it is giving me first index value i.e 2 in this case.
So basically input is like '2,3,7' and expected output is like 2,3,7.
Updation :
I can see many peoples are considering input as "'2,3,7'", consider input as '2,3,7'.
Also I have one working solution for this :
var str = '2,3,7',finalOutput=[];
var splittedValues = str.split(",");
splittedValues.forEach((value) => {
finalOutput.push(parseInt(value));
});
Is there any direct way to do this.
Thanks in advance.
Using Regex match()
DEMO: https://regex101.com/r/JhTkVB/1
var string1 = "'2,3,7'"
var string2 = "2,3,7"
console.log(string1.match(/\d+/g).map(Number));
console.log(string2.match(/\d+/g).map(Number));
The easiest way to do what you want is the following:
let str = '2, 3, 7';
let yourArray = str.split(',').map(Number);
console.log(yourArray);
This splits by the comma and then uses the map function which converts each value in an array using the function given as argument and stores them in a new array. So in this case, the function Number is called thrice with the arguments '2', '3' and '7'. Number is the constructor of the number object which also parses string to a number. The resulting array is then stored in yourArray which then has the value [2, 3, 7].
You could remove first and last characters.
var string = "'2,3,7'",
values = string.slice(1, -1);
console.log(values);
Here is another way to remove the enclosing single quotes -
var str = "'2,3,7'",
str = str.substring(1, str.length - 1)
console.log(str);
//If you need an array then
str = str.split(',').map(Number)
console.log(str);
As per your update, it seems as though your input string is simply '2,3,7'. To convert this into an array of numbers, you can use JSON.parse() by encapsulating your string in square brackets like so:
const str = '2,3,7';
const arr = JSON.parse(`[${str}]`);
console.log(arr); // [2, 3, 7]
Related
I have a string includig array symbol and double quote
var abc = '["Free WiFi","Breakfast for 2","Accommodation"]'
now i want this to convert into array and then sort this array.
the final result i want is Accomodation, Breakfast for 2, Free WiFi.
if array conversion and sorting is not require then also its fine.
how can we do it?
Just use JSON.parse and .sort:
var abc = JSON.parse('["Free WiFi","Breakfast for 2","Accommodation"]').sort().join(', ')
console.log(abc);
Another option just for fun
var abc = '["Free WiFi","Breakfast for 2","Accommodation"]';
// With help of RegExp
match = (abc.replace(/(?:\[)*\"(.*?)\"(?:\])*/g, (m,g) => g)).split(",").sort().join(', ');
// Log
console.log(match)
I'm attempting to extract strings between occurences of a specific character in a larger string.
For example:
The initial string is:
var str = "http://www.google.com?hello?kitty?test";
I want to be able to store all of the substrings between the question marks as their own variables, such as "hello", "kitty" and "test".
How would I target substrings between different indexes of a specific character using either JavaScript or Regular Expressions?
You could split on ? and use slice passing 1 as the parameter value.
That would give you an array with your values. If you want to create separate variables you could for example get the value by its index var1 = parts[0]
var str = "http://www.google.com?hello?kitty?test";
var parts = str.split('?').slice(1);
console.log(parts);
var var1 = parts[0],
var2 = parts[1],
var3 = parts[2];
console.log(var1);
console.log(var2);
console.log(var3);
Quick note: that URL would be invalid. A question mark ? denotes the beginning of a query string and key/value pairs are generally provided in the form key=value and delimited with an ampersand &.
That being said, if this isn't a problem then why not split on the question mark to obtain an array of values?
var split_values = str.split('?');
//result: [ 'http://www.google.com', 'hello', 'kitty', 'test' ]
Then you could simply grab the individual values from the array, skipping the first element.
I believe this will do it:
var components = "http://www.google.com?hello?kitty?test".split("?");
components.slice(1-components.length) // Returns: [ "hello", "kitty", "test" ]
using Regular Expressions
var reg = /\?([^\?]+)/g;
var s = "http://www.google.com?hello?kitty?test";
var results = null;
while( results = reg.exec(s) ){
console.log(results[1]);
}
The general case is to use RegExp:
var regex1 = new RegExp(/\?.*?(?=\?|$)/,'g'); regex1.lastIndex=0;
str.match(regex1)
Note that this will also get you the leading ? in each clause (no look-behind regexp in Javascript).
Alternatively you can use the sticky flag and run it in a loop:
var regex1 = new RegExp(/.*?\?(.*?)(?=\?|$)/,'y'); regex1.lastIndex=0;
while(str.match(regex1)) {...}
You can take the substring starting from the first question mark, then split by question mark
const str = "http://www.google.com?hello?kitty?test";
const matches = str.substring(str.indexOf('?') + 1).split(/\?/g);
console.log(matches);
I have a rather specific problem.
I'm using ng-csv, and because it doesn't support nested arrays, I'm turning an array into a string.
Something like this:
[
{"name":"Maria","chosen":false},
{"name":"Jenny","chosen":false},
{"name":"Ben","chosen":false},
{"name":"Morris","chosen":false}
]
Turns into:
$scope.var = "Maria, Jenny, Ben, Morris"
My problem is that when I was using the array I was able to count the number of names in the array (which I need for UI reasons), but with the string it gets tricky.
Basically, I cannot count the number of words because some names might include last name, but I thought I could count commas, and then add 1.
Any pointers on how to do just that?
If you need names itself - you may use method split of String class:
var str = "Maria, Jenny, Ben, Morris";
var arr = str.split(','); // ["Maria", " Jenny", " Ben", " Morris"]
var count = arr.length; // 4
var str = "Maria, Jenny, Ben, Morris";
var tokens = str.split(",");
The number of tokens should be captured in tokens.length. Alternately, if you don't actually need to work with the tokens directly:
var nameCount = str.split(",").length;
Why not use regex?
var _string = "Mary, Joe, George, Donald";
_string.match(/,/g).length // 3
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.
Given the following string variations:
var string = "groups/Da12312a"
var string = "groups/Da12312a/search"
var string = "groups/Da12312a/search/sam"
var string = "groups/3131"
var string = "groups/444/search"
var string = "groups/123asdadsZad/search/sam"
How can I get back just the value following groups/ and ending at the first '/'?
desired output:
Da12312a
Da12312a
Da12312a
3131
444
123asdadsZad
Using jQuery or JavaScript? Thanks
You can use the split method.
string.split("/")[1];
I would use a simple regular expression.
var str = 'groups/foo';
var matches = /groups\/([^/]*)/.exec(str);
matches will now contain an array where index 0 is "groups/100" and index 1 is "foo".
["groups/foo", "foo"]
If you want a regex, you can use the following:
/^[^\/]*?\/([^\/]*).*/
Basically the captured group yields your desired result.
Use like:
"groups/Da12312a/search".match(/^[^\/]*?\/([^\/]*).*/)
["groups/Da12312a/search", "Da12312a"]
"groups/Da12312a".match(/^[^\/]*?\/([^\/]*).*/)
["groups/Da12312a", "Da12312a"]
"groups/3131".match(/^[^\/]*?\/([^\/]*).*/)
["groups/3131", "3131"]
As you can see, in each of the cases the array index [1] is your result.
Hope that helps.
var output = string.split('/')[1];
String.split reference.
Here's a demo with your provided examples and output.