RegExp can't find a period

T

trialofmiles

Is there any reason why RegExp wouldn't be able to find a period?

str = '256.89';
a = new RegExp('(\.)');
b = /(\.)/;
alert(str.replace(a, 'x$1x'));
alert(str.replace(b, 'x$1x'));

The alert for a says
x2x56.89

However the alert for b says
256x.x89

b is the result I want, because it means that the period was found. a
is just finding a single character, as if it's ignoring the escape in
front of the period.

I've tried this in IE and Mozilla.
 
S

Steve van Dongen

Is there any reason why RegExp wouldn't be able to find a period?

str = '256.89';
a = new RegExp('(\.)');

Here's a hint:
When used in a STRING, the backslash is the escape character.
b = /(\.)/;
alert(str.replace(a, 'x$1x'));
alert(str.replace(b, 'x$1x'));

The alert for a says
x2x56.89

However the alert for b says
256x.x89

b is the result I want, because it means that the period was found. a
is just finding a single character, as if it's ignoring the escape in
front of the period.

I've tried this in IE and Mozilla.

Regards,
Steve
 
H

Harag

Here's a hint:
When used in a STRING, the backslash is the escape character.

Yeah, what you actually need to do is:

a = new RegExp('(\\.)');

when its a string.

hth
Al
 
T

trialofmiles

Steve van Dongen said:
Here's a hint:
When used in a STRING, the backslash is the escape character.

Sometimes the solution is so simple. Thank you very much.

What's strange is at one point I had written it \\. and things weren't
working the way I expected. But that was when I was trying it as part
of a larger regular expression. Another piece of the expression must
have been wrong. Things are working now.
 

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
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top