Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use javascript split method using escape character? [duplicate]

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.

like image 404
Kshitij Gupta Avatar asked Jan 15 '13 08:01

Kshitij Gupta


People also ask

How do you escape the escape character in JavaScript?

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".

How do you split a character in JavaScript?

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.

How do you split special characters?

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.

Can I use regex in Split in JavaScript?

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.


2 Answers

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.

like image 73
georg Avatar answered Nov 01 '22 11:11

georg


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 &]).

like image 31
Minko Gechev Avatar answered Nov 01 '22 11:11

Minko Gechev