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.
Here is a solution in JavaScript:
var str = 'abc&def&ghi\\&klm&nop',
str.match(/([^\\\][^&]|\\&)+/g); //['abc', 'def', 'ghi\&klm', 'nop]
It uses match
to match all characters which are ([not \ and &] or [\ and &])
.
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);
try this :
var v = "abc&def&ghi\&klm&nop";
var s = v.split("&");
for (var i = 0; i < s.length; i++)
console.log(s[i]);