javascript - 替换后,跳过字符串的该部分 - Regex Javascript

标签 javascript regex vue.js

我期望来自 HTML 输入框的一串数字,但我正在寻找一个正则表达式,以便我可以捕获字符串的某些部分并将其替换为某些内容,现在我想要的是,对于下一次迭代,正则表达式应该跳过其中的部分已处理完毕。

看看我的正则表达式

string.replace(/([\d]{10})/gm, "$1,")

迭代的预期结果

  1. 895645784578457845784578457845 来源
  2. 8956457845,7845784578,4578457845,9089 即将提供更多数据

但问题就是结果

  1. 8956457845,7845784578,4578457845
  2. 8956457845,,,7845784578,,,4578457845,,,9089

最佳答案

如果我理解正确,您希望像 string.replace(\regex\, '$1,').replace(\regex\, '$1,' 一样递归地对一个数字字符串应用 regex-replace ).replace(\regex\, '$1,'),但忽略了已经替换的部分。

下面是一种使用负向预测的解决方案。

let test = '895645784578457845784578457845' //org string
let test1 = test.replace(/(\d{10}(?!\,))/gm, "$1,")
                .replace(/(\d{10}(?!\,))/gm, "$1,")
                .replace(/(\d{10}(?!\,))/gm, "$1,") 
                // simulate recurse-replace three times
console.log(test1)

test1 += '1234567890123' //new string came
let test2 = test1.replace(/(\d{10}(?!\,))/gm, "$1,")
console.log(test2)

test2 += '1234567890123' //new string came
let test3 = test2.replace(/(\d{10}(?!\,))/gm, "$1,")
console.log(test3)

关于javascript - 替换后,跳过字符串的该部分 - Regex Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52170794/

相关文章:

javascript - 从 iFrame 获取信息 (document.getElementById)

javascript - 试图制作一个弹出式 javascript 类

regex - Grep/Regex 跨多行固定模式匹配,匹配时有特殊条件

javascript - 使用 JSON 响应的数据表

javascript - 使用正则表达式在 <p> 标签中查找除 anchor 标签以外的所有内容

python - 在 DataFrame 中使用正则表达式 - 最后 5 个字符

vue.js - 如何在 Vuex 中获取和重置模块

javascript - 无效的 prop : type check failed for prop "title". 需要值为 ** 的字符串,得到值为 ** 的数字

vue.js - 如何为图像制作预加载器?

javascript - 无法使用 javascript 获得正确的百分比 (%) 结果