regExp problem

D

datactrl

Hi, all
I tried this and it works.
------
var s1=" xxxx ";
alert(">>"+s1.replace(/^\s+/, " ")+"<<");


But why this won't work
------
var s1=" xxxx";
var reg=new RegExp("^\s+");
alert(">>"+s1.replace(reg," ")+"<<");



jack
 
L

Lee

datactrl said:
But why this won't work
var reg=new RegExp("^\s+");

The value of the string being passed to the RegExp constructor
is "^s+". The backslash is consumed as the literal string is
parsed. If you want the string to contain a backslash, you
have to escape it by preceding it with another backslash:

new RegExp("^\\s+");

or simply use a RegExp literal:

var reg=/^\s+/;
 
D

datactrl

Thanks Lee. It works.

Jack
Lee said:
datactrl said:



The value of the string being passed to the RegExp constructor
is "^s+". The backslash is consumed as the literal string is
parsed. If you want the string to contain a backslash, you
have to escape it by preceding it with another backslash:

new RegExp("^\\s+");

or simply use a RegExp literal:

var reg=/^\s+/;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top