我正在尝试找到一个 JavaScript 表达式,它可以为我提供特定位置的两个字符。
它始终是相同的调用,因此可能不会太复杂。
我总是有一个 10 个字符长的数字,我想替换前两个,即第 3 和 4 处的两个或第 5 和 6 处的两个,依此类推。
到目前为止我已经这样做了:
number.replace(/\d{2}/, index));
这会将我的前 2 位数字替换为另外 2 位数字。 但现在我想包含一些应该替换数字的位置的变量,例如:
number.replace(/\d{atposx,atpox+1}/, index));
这意味着:
01234567891
有时我想用 02 替换 01,有时用 56 替换 23。
(或类似的其他数字)。
我希望我指出了我想要的东西。
最佳答案
这个函数工作正常:
function replaceChars(input, startPos, replacement){
return input.substring(0,startPos) +
replacement +
input.substring(startPos+replacement.length)
}
用法:
replaceChars("0123456789",2,"55") // output: 0155456789
关于javascript - 查找特定位置的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7171997/