[英]js string .replace() method with index range
我需要一個 function 替換字符串,但在某些索引范圍內。 就像上面的鏈接一樣。 但是在這種情況下沒有任何答案可以幫助我。
var param = [{start: 3, end: 14}, {start: 19, end: Infinity}];
var str = 'foo foo foo foo foo foo foo';
var output = repStr(
str, // string to assign
(...param), // array of objects or a object with "start" and "end" property
new RegExp(/(foo)/g), // regex (find)
'bar' // replacement string
);
console.log(output);
// expected output: 'foo bar bar foo foo bar bar'
我想做repStr
function。 它需要支持正則表達式和數組范圍參數,我真的需要它們。 任何幫助,將不勝感激。
您可以使用String#replace
回調的倒數第二個參數(實際索引)來檢查所需范圍。
順便說一句,你的結果在給定的范圍內應該看起來有點不同。
const repStr = (string, regexp, replacement, ranges) => string.replace(regexp, (...p) => { const index = p[p.length - 2]; return ranges.some(({ start, end }) => start <= index && index <= end)? replacement: p[0] }); var param = [ {start: 3, end: 14 }, {start: 19, end: Infinity }], // ************ ******** // 012345678901234567890123456 str = 'foo foo foo foo foo foo foo', output = repStr(str, new RegExp(/(foo)/g), 'bar', param); console.log(output); // is different of 'foo bar bar foo foo bar bar'
您可以替換“參數”中所有范圍之間的子字符串中的所有“foo”實例
param.reduce((acc,cur) =>(
acc.substring(0,cur.start)+
acc.substring(cur.start,cur.end).replace(/foo/g,'bar')+
acc.substring(cur.end)
),str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.