Javascript RegExp and boundaries
Asked Answered
H

5

2

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 ?

Haplology answered 3/6, 2010 at 13:46 Comment(0)
F
11

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.

Few answered 3/6, 2010 at 13:49 Comment(2)
Also missing the capture parens: \\b(Alpha)\\bMccaleb
had the same problem.Exposed
C
2

RegExp needs to have the escape character escaped:

new RegExp('\\bAlpha\\b')
Chor answered 3/6, 2010 at 13:49 Comment(0)
P
2

This is a string issue. \b in a string literal is a backspace!

RegExp('\\bAlpha\\b','gim'); would be the correct form

Procreant answered 3/6, 2010 at 13:49 Comment(0)
L
1

There are 2 ways to write your regular expressions in Javascript

  1. literal
  2. RegExp object

In literal way, you use as you learned in your textbook, e.g. /balabala/ But in RegExp object, regular expression is written as a string.

Try the following codes, you know what string behaves in javascript.

alert("O\K");
alert("O\\K");

There's another occasion when Regexp written in a textarea or input box. For example,

http://www.pagecolumn.com/tool/regtest.htm

In this case, \ in Regexp need not be escaped.

Lx answered 3/6, 2010 at 14:8 Comment(0)
R
0

In fact you have to backslash everything in the string passed to the RegExp constructor :

var re = /my_([\w_]+-\d-)regexp/

is equivalent to :

var re = new RegExp("my_\(\[\\\w_\]+-\\\d-\)regexp")

And both match the following stupid example :

"my_very_obvious-4-regexp".match(re)
["my_very_obvious-4-regexp", "very_obvious-4-"]
Rondon answered 2/8, 2011 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.