tomsmeding
tomsmeding

Reputation: 926

Javascript respecting backslashes in input: negative lookbehind

In Javascript, I have a situation where I get input which I .split(/[ \n\t]/g) into an array. The point is that if a space is directly preceded by a backslash, I don't want the split to happen there.

E.g. is_multiply___spaced_text -> ['is','multiply','','','spaced','text']

But: is\_multiply\___spaced_text -> ['is multiply ','','spaced','text']

(Underscores used for spaces for clarity)

If this wasn't Javascript (which doesn't support lookbehinds in regex'es), I'd just use /(?<!\\)[ \n\t]/g. That doesn't work, so what would be the best way to handle this?

Upvotes: 1

Views: 241

Answers (2)

rbernabe
rbernabe

Reputation: 1072

You can reverse the string, then use negative lookahead and then reverse the strings in the array:

var pre_results = "is\\ multiply\\   spaced text".split('').reverse().join('').split(/[ \t](?!\\)/);
var results = [];
for(var i = 0; i < pre_results.length; i++) {
    results.push(pre_results[i].split('').reverse().join(''));
}
for(var i = 0; i < results.length; i++) {
    document.write(results[i] + "<br>");
}

In this example, the result should be:

['text', 'spaced', '', 'is\\ multiply\\']

Upvotes: 1

geniuscarrier
geniuscarrier

Reputation: 4249

"is\_multiply\___spaced_text".replace(/\_/, " ").replace(/_/, " ").split("_");

Upvotes: 0

Related Questions