str.replace()问题,很简单,只是我很疑惑。...

来源:百度知道 编辑:UC知道 时间:2024/09/24 06:18:04
var str="we are the world";
var restr="e";
var result = str.replace(/+restr+/g,"*");
这样写str.replace(/\+restr\+/g,"*")也不行。
但str.replace(/e/g,"*")就行,怎么把变量放里面呢?...
麻烦下面位仁兄写具体点。
不要单独写那一句。谢谢。
这个我也知道,但我还是不知道怎么把变量放进去。

完整测试代码如下:

<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>

<BODY>
<script>
var str="we are the world";
var restr="e";

var reg = new RegExp(restr,"g") ;
var result = str.replace(reg,"*");
alert("str="+str+" result="+result);
</script>
</BODY>
</HTML>

var str="we are the world";
var restr="e";
var result = str.replace(restr,"*");
以上就可以了.
replace()的第一个参数是个字符串就行了.你定义的restr就是一个字符串,直接作为第一个参数就行了.

new RegExp(restr,"g")
就可以了