在javascript中替换字符串

时间:2014-08-14 01:15:47

标签: javascript html

我有这个字符串

var str="abc test test abc";

如何用str.replace()替换第二次出现的“abc”字符串?

3 个答案:

答案 0 :(得分:2)

这是一个更通用的版本。这将适用于要在任何输入字符串中搜索和替换的任何查询字符串的 nth 出现。

var result, query = 'hello', replacement = 'good', string = 'hello hello world';

var startIndex = 0, index = 0, occurrence = 2, matches = [];

while ((index = string.indexOf(query, startIndex)) > -1) {
    matches.push(index);
    startIndex = index + query.length;
    if (matches.length === occurrence) {
        break;
    }
}

result = string.substring(0, matches[occurrence - 1]) + replacement + string.substring(matches[occurrence - 1] + query.length);

console.log(result);

http://jsfiddle.net/ze6xw8mq/

答案 1 :(得分:1)

如果您只需要替换第二个,可以使用以下代码:

var secondStart = str.indexOf("abc")+"abc".length;
str.substring(0,secondStart)+str.substring(secondStart).replace("abc","new")

我们的想法是使用indexOf将字符串拆分为两部分。

一种通用方式正在replace方法中使用回调函数:

 function replaceNthMatch(originalString, searchvalue , newvalue, matchNumber)
{
   var match = 0;
   return originalString.replace(new RegExp(searchvalue, "g"), function(found){
                      match++;
                      return (match===matchNumber)?newvalue:found;
       });
}

var str = "abc test abc test abc"
console.log(replaceNthMatch(str,"abc","new",1))
console.log(replaceNthMatch(str,"abc","new",2))
console.log(replaceNthMatch(str,"abc","new",3))

请参阅:http://jsfiddle.net/wbinglee/h09zt69x/

答案 2 :(得分:0)

如果您要替换abc第二次出现,

var str = "abc test test abc test abc"; 
str.replace(/\sabc/," ABC");

这将返回,

`abc test test ABC test abc`

如果您想要替换abc最后次出现,可以使用,

var str = "abc test test abc test abc";
str.replace(/(.*)abc(.*)/,"$1ABC$2");

哪会回来:

abc test test abc test ABC