如何仅在字符串内的某个位置替换匹配?

时间:2011-07-27 11:18:49

标签: javascript regex

所以,我有一个函数有两个参数:字符串和匹配索引要替换,我需要替换只匹配该索引。我怎么能这样做?

示例:

replace('a_a_a_a_a', 1)

结果:

a__a_a_a

5 个答案:

答案 0 :(得分:12)

看起来像:

var mystr = 'a_a_a_a_a';

function replaceIndex(string, at, repl) {
   return string.replace(/\S/g, function(match, i) {
        if( i === at ) return repl;

        return match;
    });
}

replaceIndex(mystr, 2, '_');

上面的代码使用了这个事实,.replace()可以将funarg(函数参数)作为第二个参数。该回调在匹配的正则表达式模式的当前匹配和该匹配的索引中传递(以及我们对此不感兴趣的其他一些)。现在,这是我们完成所需结果所需的所有信息。我们写了一个小函数,希望有三个参数:

  • 要修改的字符串
  • 我们希望改变的指数
  • 该职位的替换字符

答案 1 :(得分:9)

对于像我这样认为正则表达式具有神秘色彩的人来说,这里也是“纯粹的JavaScript”方式:

function CustomReplace(strData, strTextToReplace, strReplaceWith, replaceAt) {
    var index = strData.indexOf(strTextToReplace);
    for (var i = 1; i < replaceAt; i++)
        index = strData.indexOf(strTextToReplace, index + 1);
    if (index >= 0)
        return strData.substr(0, index) + strReplaceWith + strData.substr(index + strTextToReplace.length, strData.length);
    return strData;
}

用法:

var mystr = 'a_a_a_a_a';
var newstr = CustomReplace(mystr, "_", "__", 2); //replace the second appearance

实时测试案例:http://jsfiddle.net/tXx5n/2/

答案 2 :(得分:1)

Javascript match返回一个数组,如果有多个匹配,那么你可以这样:

var string = "....";
var patt1 = /..../gi;
var results = string.match(patt1);
var newString = results.splice(i, i).join();

您可以在特定情况下使用split而不是匹配:

var results = string.split("_");
var newString = results.splice(i, i).join("_");

这取决于您的输入数据如何变化以及您需要进行拆分/匹配的位置(这就是为什么我没有在上面指定任何正则表达式,拆分示例已完成)...

答案 3 :(得分:0)

使用带g标志的正则表达式匹配 var str =“test string”.match(/ t / g)输出将是匹配字符串的数组,在这种情况下为“t” [T,T,T]

答案 4 :(得分:0)

您需要使用function parameter of the replace function,并维护匹配的索引(i)。

&#13;
&#13;
function replaceAt(string, replaceThis, replaceWith, at) {
  let i = 0;
  if (Array.isArray(at)) {
    return string.replace(replaceThis, (match, offset) => at.includes(i++) ? replaceWith : match)
  } else if (Number.isInteger(at)) {
    return string.replace(replaceThis, (match, offset) => i++ === at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log(replaceAt("aaaaabcde", /a/g, ".", [2, 0])); // ".a.aaabcde"
console.log(replaceAt("aaaaabcde", /a/g, ".", 2)); // "aa.aabcde"

String.prototype.replaceAt = function(replaceThis, replaceWith, at) {
  let string = this, i = 0;
  if (Array.isArray(at)) { // e.g. console.log("aaaaabcde".replaceAt(/a/g, ".", 2)); => "aa.bcde"
    return string.replace(replaceThis, (match, offset) => at.includes(offset) ? replaceWith : match)
  } else if (Number.isInteger(at)) { //e.g. console.log("aaaaabcde".replaceAt(/a/g, ".", [2, 0])); => ".a.bcde"
    return string.replace(replaceThis, (match, offset) => offset === at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log("aaaaabcde".replaceAt(/a/g, ".", [2, 0])); // ".a.aaabcde"
console.log("aaaaabcde".replaceAt(/a/g, ".", 2)); // "aa.aabcde"

function replaceExceptAt(string, replaceThis, replaceWith, at) {
  let i = 0;
  if (Array.isArray(at)) { // e.g. console.log(replaceExceptAt("aaaaabcde", /a/g, ".", 2); => "..a..bcde"
    return string.replace(replaceThis, (match, offset) => !at.includes(i++) ? replaceWith : match)
  } else if (Number.isInteger(at)) { //e.g. console.log(replaceExceptAt("aaaaabcde", /a/g, ".", [2, 0])); => "a.a..bcde"
    return string.replace(replaceThis, (match, offset) => i++ !== at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log(replaceExceptAt("aaaaabcde", /a/g, ".", [2, 0])); // "a.a..bcde"
console.log(replaceExceptAt("aaaaabcde", /a/g, ".", 2)); // "..a..bcde"

String.prototype.replaceExceptAt = function(replaceThis, replaceWith, at) {
  let string = this, i = 0;
  if (Array.isArray(at)) { // e.g. console.log("aaaaabcde".replaceExceptAt(/a/g, ".", 2); => "..a..bcde"
    //return string.replace(replaceThis, (match, offset) => !at.includes(offset) ? replaceWith : match)
    return string.replace(replaceThis, (match, offset) => !at.includes(i++) ? replaceWith : match)
  } else if (Number.isInteger(at)) { //e.g. console.log(replaceAt("aaaaabcde", /a/g, ".", [2, 0])); => "a.a..bcde"
    return string.replace(replaceThis, (match, offset) => i++ !== at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log("aaaaabcde".replaceExceptAt(/a/g, ".", [2, 0])); // "a.a..bcde"
console.log("aaaaabcde".replaceExceptAt(/a/g, ".", 2)); // "..a..bcde"
&#13;
&#13;
&#13;