如何仅在字符串内的某个位置替换匹配? [英] How can I replace a match only at a certain position inside the string?

查看:247
本文介绍了如何仅在字符串内的某个位置替换匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that?

示例:

replace('a_a_a_a_a', 1)

结果:

a__a_a_a


推荐答案

看起来像:

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 (功能参数)作为第二个参数。该回调在匹配的正则表达式模式的当前匹配和该匹配的索引中传递(以及我们对此不感兴趣的其他一些)。现在,这是我们完成所需结果所需的所有信息。我们写一个小函数wish需要三个参数:

The above code makes usage of the fact, that .replace() can take a funarg (functional argument) as second parameter. That callback is passed in the current match of the matched regexp pattern and the index from that match (along with some others which we are not interested in here). Now that is all information we need to accomplish your desired result. We write a little function wish takes three arguments:


  • 要修改的字符串

  • 索引我们希望更改

  • 该职位的替换字符

这篇关于如何仅在字符串内的某个位置替换匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆