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.
To use a special character as a regular one, prepend it with a backslash: \. . That's also called “escaping a character”. For example: alert( "Chapter 5.1".
The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated.
To split a string by special characters, call the split() method on the string, passing it a regular expression that matches any of the special characters as a parameter. The method will split the string on each occurrence of a special character and return an array containing the results.
You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.
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.
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 &])
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With