-1
<html>
<body>

<script type="text/javascript">

var str="Welcome to Microsoft! ";
var val="Microsoft!";

document.write(str.replace('/'+val'+/gi', "W3Schools"));

</script>

</body>
</html>

this is not working, how to use val dynamically ?

Yoshi
  • 51,516
  • 13
  • 81
  • 100
Rosh
  • 1,496
  • 4
  • 19
  • 33
  • http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript –  Mar 28 '12 at 11:32

2 Answers2

2

You need to make the argument for replace() a regular expression. If you put it in quotes, it is simply a string. Use the RegExp constructor instead:

document.write(str.replace(new RegExp(val, 'gi'), "W3Schools"));
Niko
  • 25,682
  • 7
  • 85
  • 108
1

You cannot construct a regex literal trough string concatenation

try:

var str="Welcome to Microsoft! ";
var val="Microsoft!";

document.write(str.replace(new RegExp(val, 'gi'), "http://www.w3fools.com"));

Ref: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Yoshi
  • 51,516
  • 13
  • 81
  • 100