Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript RegExp and boundaries

A colleague asked me about a Regular expression problem, and I can't seem to find and answer for him.

We're using boundaries to highlight certain lengths of text in a text editor, but here's some sample code that shows the problem:

<script type="text/javascript">
var str = "Alpha , Beta, Gamma Delta Epsilon, AAlphaa, Beta Alpha<br/>";
var rx = new RegExp('\bAlpha\b','gim');

document.write(str.replace(/\b(Alpha)\b/gim, '-- $1 --'));
document.write(str.replace(rx, '== $1 =='));
</script>

The issue is, the first literal str.replace works, but the RegExp option doesn't.

I've got the same behaviour in IE and FF, anyone know why ?

like image 478
Russ Clarke Avatar asked May 24 '26 11:05

Russ Clarke


2 Answers

I'm guessing it doesn't work because you need to escape the backslashes in your string that you pass to RegExp. You have this:

var rx = new RegExp('\bAlpha\b','gim');

You need this:

var rx = new RegExp('\\bAlpha\\b','gim');

The string you passed to RegExp has 2 backspace characters in it, since \b is the escape sequence for inserting a backspace into a string. You need to escape each backslash with another backslash.

like image 116
A. Levy Avatar answered May 26 '26 01:05

A. Levy


RegExp needs to have the escape character escaped:

new RegExp('\\bAlpha\\b')
like image 24
Andy E Avatar answered May 26 '26 02:05

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!