Ramtin Soltani Ramtin Soltani - 7 months ago 33
Javascript Question

Regex to find characters not having a certain character before them

I have these strings in Javascript:

var string1 = '#23 the id of this report is \\# 23';
var string2 = '# \\# \\# # \\\\# #';


I want to do a
.replace()
that replaces all
#
with no
\\
before them with
\\#
, but can't write the correct regex.

Result for
string2
should be
\\# \\# \\# \\# \\\\# \\#


Any thoughts?

Answer

You can target hash marks with no backslashes before them by first matching hash marks with backslashes before them, then as an alternative (using the alternation operator, also known as the pipe, |) try a hash mark by itself, which will therefore match hash marks with no backslash before it, and replacing in either case with \#:

var string2       = '# \\# \\# # \\\\# #';
var maybe_escaped = /\\#|#/g;
var result        = string2.replace(maybe_escaped, '\\#');

document.getElementById('result').textContent = JSON.stringify(result);
<div id='result' style="font-family: monospace; "></div>

Comments