0

I am desperate - I don't see what I'm doing wrong. I try to replace all occurrences of '8969' but I always get the original string (no matter whether tmp is a string or an int). Maybe it's already too late, maybe I'm blind, ...

var tmp = "8969";
alert("8969_8969".replace(/tmp/g, "99"));

Can someone help me out?

1
  • 1
    Why do you use such expression /tmp/g? Commented May 1, 2012 at 21:41

5 Answers 5

8

The / characters are the container for a regular expression in this case. 'tmp' is therefore not used as a variable, but as a literal string.

var tmp = /8969/g;
alert("8969_8969".replace(tmp, "99"));
Sign up to request clarification or add additional context in comments.

Comments

5
alert("8969_8969".replace(/8969/g, "99"));

or

var tmp = "8969"
alert("8969_8969".replace(new RegExp(tmp,"g"), "99")); 

Live DEMO

1 Comment

I know this works, but I have the value in a variable ... Even if I write var tmp = 8969; it doesn't work ...
3

Dynamic way of handling a regex:

var nRegExp = new RegExp("8969", 'g');
alert("8969_8969".replace(nRegExp, "99"));

Comments

2

/tmp/g. This is a regex looking for the phrase "tmp". You need to use new RegExp to make a dynamic regex.

alert("8969_8969".replace(new RegExp(tmp,'g'), "99"));

Comments

-1

Javascript doesn't support that usage of tmp, it will try to use 'tmp' literally, as a regex pattern.

"8969_8969".replace(new RegExp(tmp,'g'), "99")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.