龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > Javascript编程 >

javascript replace()实现多次替换的方法

时间:2012-12-29 08:41来源:未知 作者:admin 点击:
分享到:
本文章来告诉你关于js replace解决只能替换一次 的问题,有需要了解的朋友可以参考一下本教程。 定义和用法 replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则
本文章来告诉你关于js replace解决只能替换一次 的问题,有需要了解的朋友可以参考一下本教程。

定义和用法
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

语法
stringObject.replace(regexp/substr,replacement)参数 描述
regexp/substr 必需。规定子字符串或要替换的模式的 RegExp 对象。

请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。
 
replacement 必需。一个字符串值。规定了替换文本或生成替换文本的函数。

返回值
一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。
示例
   下面的示例演示了 replace 方法将第一次出现的单词 "The" 替换为单词 "A" 的用法。 
   

 代码如下
   function ReplaceDemo(){
    var r, re; // 声明变量。
    var ss = "The man hit the ball with the bat.n";
    ss += "while the fielder caught the ball with the glove.";
    re = /The/g; // 创建正则表达式模式。
    r = ss.replace(re, "A"); // 用 "A" 替换 "The"。
    return(r); // 返回替换后的字符串。
   }

更多详细内容请查看:http://www.111cn.net/wy/99/js_replace_replaceall.htm

上面的只能替换一次,下面我们来看看实现多次替换的方法

 代码如下

<script language="javascript">
$(function(){
 var str = 'rtsp://112.5.172.36:10082/1d8a097f_51bf_4ef2_8380_71d63e9fb97a/c1v1.3gp';
    var re = /://.*$/i;
    if(re.test(str)){
   var newStr = str.substring(str.indexOf("://")+3, str.length);
   var strarray = newStr.split("/");
   alert(strarray[0].substring(0, strarray[0].indexOf(":")));
  
   alert(replaceStr(strarray[1]));
 }
 function replaceStr(str){
    var newstring = str;
    while(newstring.indexOf("_") > 0)
    {
    newstring = newstring.replace("_","-");
     }
 return newstring;
   }
});
</script>


精彩图集

赞助商链接