简体   繁体   中英

Replace multiple strings with known positions

So i have a string like this

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do

And have replacement data like this replace1: 0-5,10-15 replace2: 30-33,40-43

Meaning replace all characters from 0-5 with "replace1" Then also replace characters 10-15 with "replace1"

Also replace 30-33 with "replace2" etc.

How would I do this in the best way? My only idea would be recalculating the indexes everytime I replace something. Otherwise when I insert something into the the string it will make the replacement data invalid since the indices are different.

I'm trying to implement this in javascript.

message = message.substring(0, start) + replacement + message.substring(end + replacement.length);

This is the stupid version since it only works once and then the next replacement data index is off.

I don't think a regex is the right tool here. Instead, iterate backwards , eg indicies 40-43, then indicies 30-33, etc, replacing as you go:

 let str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do'; const replacements = [ [0, 5, 'replace1'], [10, 15, 'replace2'], [30, 33, 'replace3'], [40, 43, 'replace4'], ]; for (const [start, end, replacement] of replacements.reverse()) { str = str.slice(0, start) + replacement + str.slice(end); } console.log(str);

maybe you can use an array to store the chopped substring like this

var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do";
var arr = [];

while (str.length > 5) {
  arr.push(str.slice(5, 10))
  str = str.slice(10)
}

var result = arr.reduce(function(a, c, i) {
  var token = "replace" + Math.ceil((i + 1)/2);
    return a + token + c;
}, "");

console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM