2012-03-28 90 views
-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> 

這不工作,如何動態使用val?javascript中的動態全局值替換

+0

http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript – boring 2012-03-28 11:32:08

回答

2

您需要爲replace()指定正則表達式的參數。如果你把它放在引號中,它只是一個字符串。使用正則表達式構造來代替:

document.write(str.replace(new RegExp(val, 'gi'), "W3Schools")); 
+0

fyn,thankx – Rosh 2012-03-29 04:45:03