<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 ?
<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 ?
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"));
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