Javascript RegExp and Borders

A colleague asked me about the problem of regular expression, and I can not find and answer for it.

We use borders to highlight specific lengths of text in a text editor, but here is an example of 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 problem is that the first literal str.replace works, but the RegExp parameter does not work.

I have the same behavior in IE and FF, does anyone know why?

+2
javascript regex word-boundary
source share
5 answers

I assume this will not work, because you need to avoid the backslashes in your string that you pass into RegExp. You have the following:

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

You need the following:

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

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

+10
source share

RegExp must have an escape character:

 new RegExp('\\bAlpha\\b') 
+2
source share

This is a string problem. \b in a string literal is the inverse space!

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

+2
source share

There are two ways to write your regular expressions in javascript

  • literal
  • RegExp Object

Literally, you use, as you learned in your textbook, for example. / Balabala / But in the RegExp object, the regular expression is written as a string.

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

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

There is another case where Regexp is written in a text field or in an input field. For example,

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

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

+1
source share

In fact, you need the backslash in the string passed to the RegExp constructor:

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

equivalent to:

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

And both correspond to the following stupid example:

 "my_very_obvious-4-regexp".match(re) ["my_very_obvious-4-regexp", "very_obvious-4-"] 
0
source share

Source: https://habr.com/ru/post/650471/


All Articles