If I had a string with three values that is delimited by spaces, now I want to store these three values in three variables or maybe an array, how to do?
Use split().
For example:
var variables = delimited_string.split(/\s+/);
If you know it is separated by a single space, avoid using a regular expression with the following:
var variables = delimited_string.split(' ');
Got it: I use String.split(pattern)
var str = "I am confused".split(/\s/g)
Related
I have a string which represents the attributes of a function:
str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
There are 3 attributes: My Communities, null, {...}
I would like to split the string into array containing these 3 values but without splitting the object literal.
I believe I need to construct a regular expression which would allow me to str.split(//) however I am not able to get the 3 attributes which I need.
Any help would be appreciated.
If be sure the string doesn't have extra ' in the value of each element, I think one quick way is treat it as one JSON string, then pull out the element you need.
The codes are like below:
let str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
console.log(JSON.parse('[' + str.replace(/'/g, '"') +']'))
If you don't have nested braces and if comma is always before {, then you can do this:
var re = /(\{[^}]+\})/;
var result = [];
str.split(re).forEach(function(part) {
if (part.match(re) {
result.push(part);
} else {
var parts = part.split(',').map((x) => x.trim()).filter(Boolean);
result = result.concat(parts);
}
});
if you have something before braces or if braces are nested you will need more compicated parser.
My first suggestion would be to find a different way to get the string formatted coming into your system. If that is not feasible, you can do the following regex (note: it is super fragile):
/\,(?![^{]*})/
and get the groupings like so:
list = str.split(/\,(?![^{]*})/)
I would use the second limit parameter of split() (docs) to stop cutting before the object literal:
var str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}";
console.log(str.split(', ', 3));
I am doing some JavaScript coding and have to process a string to a array.
The original string is this: "red,yellow,blue,green,grey"
What I want to get is an array like this: ["red","yellow","blue","green","grey"]
I have tried to write a function to do this, use indexOf() to get the position of commas then do some further processing. But I think it's to heavy this way. Is there a better way to use regular expression or some existed JavaScript method to implement my purpose?
Thanks all.
use string.split function to split the original string by comma.......
string.split(",")
You can use split:
The split() method splits a String object into an array of strings by separating the string into substrings.
var arr = "red,yellow,blue,green,grey".split(',');
OR
You can also use regex:
var arr = "red,yellow,blue,green,grey".match(/\w+/g);
Try the string.split() method. For further details refer to:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
you can use .split() function.
Example
.split() : Split a string into an array of substrings:
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
alert(res);
You can use following regular expression ..
[^,]*
I am having strings like following in javascript
lolo dolo:279bc880-25c6-11e3-bc22-3c970e02b4ec
i want to extract the string before : and after it and store them in a variable. I am not a regex expert so i am not sure how to do this.
No regex needed, use .split()
var x = 'lolo dolo:279bc880-25c6-11e3-bc22-3c970e02b4ec'.split(':');
var before = x[0]
var after = x[1]
Make use of split(),No need of regex.
Delimit your string with :,So it makes your string in to two parts.
var splitter ="lolo dolo:279bc880-25c6-11e3-bc22-3c970e02b4ec".split(':');
var first =splitter[0];
var second =splitter[1];
I'm trying to split a huge string that uses "}, {" as it's separator.
If I use the following code will I get split it into it's own string?
var i;
var arr[];
while(str) {
arr[i] = str.split("/^}\,\s\{\/");
}
First, get rid of the while loop. Strings are immutable, so it won't change, so you'll have an infinite loop.
Then, you need to get rid of the quotation marks to use regex literal syntax and get rid of the ^ since that anchors the regex to the start of the string.
/},\s\{/
Or just don't use a regex at all if you can rely on that exact sequence of characters. Use a string delimiter instead.
"}, {"
Also, this is invalid syntax.
var arr[];
So you just do the split once, and you'll end up with an Array of strings.
All in all, you want something like this.
var arr = str.split(/*your split expression*/)
var arr = str.split(/[\{\},\s]+/)
var s = 'Hello"}, {"World"}, {"From"}, {"Ohio';
var a = s.split('"}, {"');
alert(a);
I want to check if a single character matches a set of possible other characters so I'm trying to do something like this:
str.charAt(0) == /[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/
since it doesn't work is there a right way to do it?
Use test
/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/.test(str.charAt(0))
Yes, use:
if(str.charAt(0).match(/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/))
charAt just returns a one character long string, there is no char type in Javascript, so you can use the regular string functions on it to match against a regex.
Another option, which is viable as long as you are not using ranges:
var chars = "[].,-/#!$%^&*;:{}=-_`~()";
var str = '.abc';
var c = str.charAt(0);
var found = chars.indexOf(c) > 1;
Example: http://jsbin.com/esavam
Another option is keeping the characters in an array (for example, using chars.split('')), and checking if the character is there:
How do I check if an array includes an object in JavaScript?