Possible Duplicate:
how to split a string in js with some exceptions
For example if the string is:
abc&def&ghi\&klm&nop
Required output is array of string
['abc', 'def', 'ghi\&klm', 'nop]
Please suggest me the simplest solution.
Possible Duplicate:
how to split a string in js with some exceptions
For example if the string is:
abc&def&ghi\&klm&nop
Required output is array of string
['abc', 'def', 'ghi\&klm', 'nop]
Please suggest me the simplest solution.
You need match:
"abc&def&ghi\\&klm&nop".match(/(\\.|[^&])+/g)
# ["abc", "def", "ghi\&klm", "nop"]
I'm assuming that your string comes from an external source and is not a javascript literal.
var str = "abc&def&ghi\\&klm&nop";
var test = str.replace(/([^\\])&/g, '$1\u000B').split('\u000B');
You need to replace \& with double slashes
how to split a string in js with some exceptions
test will contain the array you need
You can do with only oldschool indexOf:
var s = 'abc&def&ghi\\&klm&nop',
lastIndex = 0,
prevIndex = -1,
result = [];
while ((lastIndex = s.indexOf('&', lastIndex+1)) > -1) {
if (s[lastIndex-1] != '\\') {
result.push(s.substring(prevIndex+1, lastIndex));
prevIndex = lastIndex;
}
}
result.push(s.substring(prevIndex+1));
console.log(result);
match(\\.|[^delim]), rather thansplit. See my answer below.