11

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.

5
  • Although this answer applies to Java, it does tackle the same issue, and shouldn't be difficult to translate: stackoverflow.com/questions/3870415/… Commented Jan 15, 2013 at 8:41
  • 3
    @cheeseweasel unfortunately, as js does not implement "negative lookbehind", it will be not that easy to translate. ;) Commented Jan 15, 2013 at 8:42
  • 1
    some helpful reading: Mimicking Lookbehind in JavaScript Commented Jan 15, 2013 at 8:48
  • @Yoshi, thanks, I was just looking into it and found that out myself. At least there have been some interesting workarounds offered! :) Commented Jan 15, 2013 at 9:00
  • 1
    Note for googlers: the duplicate question doesn't provide a definitive answer to this. Since javascript re dialect lacks lookbehinds, the javascript way to split a string with escaped delimiters is to use match(\\.|[^delim]), rather than split. See my answer below. Commented Jan 15, 2013 at 14:01

5 Answers 5

12

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

2
  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

Comments

1

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);

Comments

-7

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.