Javascript - regular expression to split string on unescaped character, e.g. | but ignore \|

Another solution:

"1|test pattern|prefix|url \\| title |postfix"
.replace(/([^\\])\|/g, "$1$1|")
.split(/[^\\]\|/);

That said, you'll need to escape your backslash in the initial string with another backslash to make it work:

"1|test pattern|prefix|url \\| title |postfix"
                           ^

Working demo available here.


Unfortunately Javascript does not support lookbehinds. I see no easy solution but the following might be suitable as workaround:

// use two backslashes in your string!
var string = '1|test pattern|prefix|url \\| title |postfix';

// create an arbitrary unique substitute character
var sub = "-";

string.replace(/\\\|/g,sub).split(/\|/);

/* replace the substituted character again in your array of strings */

Alternatively you could use something like this:

string.split(//\|\b//)

However this might fail in some circumstances when there are whitespaces involved.