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.

Community
  • 1
  • 1
Kshitij Gupta
  • 410
  • 1
  • 3
  • 9
  • Although this answer applies to Java, it does tackle the same issue, and shouldn't be difficult to translate: http://stackoverflow.com/questions/3870415/splitting-a-string-that-has-escape-sequence-using-regular-expression-in-java – Sam Peacey Jan 15 '13 at 08:41
  • 3
    @cheeseweasel unfortunately, as js does not implement "negative lookbehind", it will be not that easy to translate. ;) – Yoshi Jan 15 '13 at 08:42
  • 1
    some helpful reading: [Mimicking Lookbehind in JavaScript](http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript) – Yoshi Jan 15 '13 at 08:48
  • @Yoshi, thanks, I was just looking into it and found that out myself. At least there have been some interesting workarounds offered! :) – Sam Peacey Jan 15 '13 at 09: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. – georg Jan 15 '13 at 14:01

5 Answers5

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.

georg
  • 211,518
  • 52
  • 313
  • 390
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 &]).

Zachary Raineri
  • 148
  • 1
  • 12
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
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

Community
  • 1
  • 1
Ferry Kobus
  • 2,009
  • 2
  • 14
  • 18
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);
bjornd
  • 22,397
  • 4
  • 57
  • 73
-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]);
Iswanto San
  • 18,263
  • 13
  • 58
  • 79