用javascript替换字符串中第n个出现的数字

用javascript替换字符串中第n个出现的数字

本文介绍了用javascript替换字符串中第n个出现的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题曾经被问过,但是我没有成功解决问题.我有一个包含数字的字符串,例如

This question been asked before, but I did not succeed in solving the problem.I have a string that contains numbers, e.g.

var stringWithNumbers = "bla_3_bla_14_bla_5";

我想用javascript代替数字的第n次出现(例如第2次出现).我没有比这更远

I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than

var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);

这只会更改第一个数字.建议使用诸如 $ 1 之类的后向引用,但这对我没有帮助.

This only changes the first number.It was suggested to use back references like $1, but this did not help me.

例如,结果应为

"bla_3_bla_xy_bla_5" //changed 2nd occurence

推荐答案

您可以定义与 all 匹配的正则表达式,并将回调方法作为第二个参数传递给 replace 方法并在其中添加一些自定义逻辑:

You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:

var mystr = 'bla_3_bla_14_bla_5';

function replaceOccurrence(string, regex, n, replace) {
   var i = 0;
   return string.replace(regex, function(match) {
        i+=1;
        if(i===n) return replace;
        return match;
    });
}
console.log(
   replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)

在这里, replaceOccurrence(mystr,/\ d +/g,2,'NUM')使用 mystr ,用/\ d +搜索所有数字序列/g ,并且在第二次出现时,它将替换为 NUM 子字符串.

Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.

这篇关于用javascript替换字符串中第n个出现的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:32