JavaScript 将子字符串替换为重复次数的值
javascript to replace a substring with value of how many times it is repeated
我在给这个问题起正确的标题时遇到了一点困难。下面是我想要的示例。
var originalString ="hello all, This is a hello string written by hello";
var substringToBeCounted = "hello";
var expectedString ="1 hello all, This is a 2 hello string written by 3 hello; .
我正在烦恼地在整个字符串中附加"hello"实例的计数。
这是我到目前为止得到的工作解决方案:
var hitCount = 1;
var magicString = "ThisStringWillNeverBePresentInOriginalString";
while(originalString .match(substringToBeCounted ).length >0){
originalString = originalString .replace(substringToBeCounted , hitCount + magicString );
hitCount++;
}
var re = new RegExp(magicString,'gi');
originalString = originalString.replace(re, subStringToBeCounted);
解释上面的代码:我正在循环,直到 match 在原始字符串中找到"hello",并且在循环中,我正在将 hello 更改为一些带有我想要的计数的奇怪字符串。
最后,我将奇怪的字符串替换回hello。
这个解决方案对我来说看起来很笨拙。
有没有聪明的解决方案来解决这个问题。
谢谢
替换接受函数作为替换;这样你就可以返回你想要的东西
var originalString = "hello all, This is a hello string written by hello";
var substringToBeCounted = "hello";
var count = 0;
var reg = new RegExp(substringToBeCounted, 'g');
// this could have just been /hello/g if it isn't dynamically created
var replacement = originalString.replace(reg, function(found) {
// hint: second function parameter is the found index/position
count++;
return count + ' ' + found;
});
为了使它更可重用:
function counterThingy(haystack, needle) {
var count = 0;
var reg = new RegExp(needle, 'g');
return haystack.replace(reg, function(found) {
count++;
return count + ' ' + found;
});
}
var whatever = counterThingy(originalString, substringToBeCounted);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
相关文章:
- 字符串替换-不支持格式字符'}'
- Unicode字符串替换不适用于完整的变音符号阿拉伯文本
- Javascript 将字符串替换为
返回为空 - 字符串替换只替换第一个匹配项,可以'不要让它全球化
- javascript字符串替换$1(如果它是某个值)
- 字符串替换正则表达式,开头为空格
- 将 url 中的一个字符串替换为另一个字符串
- 在HTML文本框中查找某些子字符串,然后用其他字符串替换它们
- 我想使用replace函数扫描json对象,然后用字符串替换匹配的单词
- 字符串替换为从右向左的语言(阿拉伯语)
- 将字符串替换为用户键入的文本
- 字符串替换javascript
- JavaScript 将多行字符串替换为多行字符串
- Javascript字符串替换不起作用
- 字符串替换不'当通过android webView JavascriptInterface传递字符串时无法工作
- 我正在尝试用另一个字符串替换一个字符串
- 字符串替换最后一个字符出现的斜杠
- 将具有的字符串替换为$
- 基于查询字符串替换HTML
- Javascript字符串替换在满足长度而不是instantanoeus之前不会生效