0

I have a problem. I have a string - "\,str\,i,ing" and i need to split by comma before which not have slash. For my string - ["\,str\,i", "ing"]. I'm use next regex

myString.split("[^\],", 2)

but it's doesn't worked.

4
  • You realize the second argument 2 is limiting the number of splits to 2? What is the output of myString.split("[^\],", 2) now? Commented Jun 14, 2012 at 15:18
  • 3
    Try myString.split(/[^\],/g), "[^\]," is a string not a regular expression. Commented Jun 14, 2012 at 15:22
  • Actually, I don't think you can use split for this, since it will consume the non-backslash character before the string and Javascript regexes don't support lookbacks. Commented Jun 14, 2012 at 15:27
  • It looks like you're trying to parse a line of CSV with RegEx, but JS doesn't have the ability to do lookbehinds. Commented Jun 14, 2012 at 15:27

6 Answers 6

3

Well, this is ridiculous to avoid the lack of lookbehind but seems to get the correct result.

"\\,str\\,i,ing".split('').reverse().join('').split(/,(?=[^\\])/).map(function(a){
    return a.split('').reverse().join('');
}).reverse();

//=> ["\,str\,i", "ing"]
Sign up to request clarification or add additional context in comments.

1 Comment

Uh, this looks even more complicated than mine :-) But cool idea to use lookahead, +1
2

Not sure about your expected output but you are specifying string not a regex, use:

var arr = "\,str\,i,ing".split(/[^\\],/, 2);
console.log(arr);

To split using regex, wrap your regex in /..../

2 Comments

This will remove the character before the comma as well.
@kennebec: Well as I have said in my answer, not sure about expected output but have pointed out the way to use regex in conjunction with split
0

This is not easily possible with js, because it does not support lookbehind. Even if you'd use a real regex, it would eat the last character:

> "xyz\\,xyz,xyz".split(/[^\\],/, 2)
["xyz\\,xy", "xyz"]

If you don't want the z to be eaten, I'd suggest:

var str = "....";
return str.split(",").reduce(function(res, part) {
    var l = res.length;
    if (l && res[l-1].substr(-1) == "\\" || l<2)
//      ^                        ^^          ^
//  not the first         was escaped      limit
        res[l-1] += ","+part;
    else
        res.push(part);
    return;
}, []);

Comments

0

Reading between the lines, it looks like you want to split a string by , characters that are not preceded by \ characters.

It would be really great if JavaScript had a regular expression lookbehind (and negative lookbehind) pattern, but unfortunately it does not. What it does have is a lookahead ((?=) )and negative lookahead ((?!)) pattern. Make sure to review the documentation.

You can use these as a lookbehind if you reverse the string:

var str,
    reverseStr,
    arr,
    reverseArr;
//don't forget to escape your backslashes
str = '\\,str\\,i,ing';

//reverse your string
reverseStr = str.split('').reverse().join('');

//split the array on `,`s that aren't followed by `\`
reverseArr = reverseStr.split(/,(?!\\)/);

//reverse the reversed array, and reverse each string in the array
arr = reverseArr.reverse().map(function (val) {
    return val.split('').reverse().join('');
});

Comments

0

You picked a tough character to match- a forward slash preceding a comma is apt to disappear while you pass it around in a string, since '\,'==','...

var s= 'My dog, the one with two \\, blue \\,eyes, is asleep.';
var a= [], M, rx=/(\\?),/g;
while((M= rx.exec(s))!= null){
    if(M[1]) continue;
    a.push(s.substring(0, rx.lastIndex-1));
    s= s.substring(rx.lastIndex);
    rx.lastIndex= 0;
};
a.push(s);


/*  returned value: (Array)
My dog 
the one with two \, blue \,eyes 
is asleep.
*/

Comments

0

Find something which will not be present in your original string, say "@@@". Replace "\\," with it. Split the resulting string by ",". Replace "@@@" back with "\\,".

Something like this:

<script type="text/javascript">
   var s1 = "\\,str\\,i,ing";
   var s2 = s1.replace(/\\,/g,"@@@");
   console.log(s2);
   var s3 = s2.split(",");
   for (var i=0;i<s3.length;i++)
   {
       s3[i] = s3[i].replace(/@@@/g,"\\,");
   }
   console.log(s3);
 </script>

See JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.