Home > Mobile >  How to replace list of words with <span> tag at multiple indexes in Javascript
How to replace list of words with <span> tag at multiple indexes in Javascript

Time:07-20

I have a response of parent string which I have to modify and replace with the provided start and end indexes.

let parentString = '\r\nManchester United won\r\nManchester City lost\r\nLeeds United tied'

let replaceValues = 
    {value: 'Manchester United', startIndex: 2, endIndex: 19}
    {value: 'Manchester City', startIndex: 25, endIndex: 40}
    {value: 'Leeds United', startIndex: 47, endIndex: 59}

Expected Final Result:

enter image description here

I tried below approach but was not successful

replaceAt(input: string, index: number, replacement: string, source: string) {
    return (
      input.substring(0, index)  
      replacement  
      input.substring(index   source.length)
    );
  }

Usage:

replaceValues.forEach((replaceMatch: any) => {
        parentString =  this.replaceAt(
              parentString,
              replaceMatch.startIndex,
              "<span class='replace-text-{{i}}'>${replaceMatch.value}</span>",
              replaceMatch.value
            );

please ignore my example names couldn't think anything more

CodePudding user response:

If you don't want to use regex you can try this code :

let parentString = '\r\nManchester United won\r\nManchester City lost\r\nLeeds United tied'

let replaceValues = [
    {value: 'Manchester United', startIndex: 2, endIndex: 19},
    {value: 'Manchester City', startIndex: 25, endIndex: 40},
    {value: 'Leeds United', startIndex: 47, endIndex: 59},
];

replaceValues.sort((a,b) => b.startIndex - a.startIndex);

function replaceAt(input, start, end, value) {
    let str = input.split('')
    str.splice(start, end - start, value);
    return str.join('');
}

for(let replace of replaceValues) {
    parentString = replaceAt(parentString,replace.startIndex, replace.endIndex, `<span class='replace-text-{{i}}'>${replace.value}</span>`);
}

console.log(parentString);

// Output :
// <span class='replace-text-{{i}}'>Manchester United</span> won
// <span class='replace-text-{{i}}'>Manchester City</span> lost
// <span class='replace-text-{{i}}'>Leeds United</span> tied

I don't know where does {{i}} comes from, but I think you can easily fill it will the correct value

CodePudding user response:

Probably not the cleanest solution but it works:

Use values to replace names with their 'html' equivalent within the parent string

replaceValues.forEach(item => {
  parentString = parentString.replace(item.value, `<span>${item.value}</span>`)
})

Now you have a string that is like this:

\r\n<span>Manchester United</span> won\r\n<span>Manchester City</span> lost\r\n<span>Leeds United</span> tied

So now you may want this string as an array of html content

let contentsArray = parentString.split("\r\n")

Now we have this:

 [
  "",
  "<span>Manchester United</span> won",
  "<span>Manchester City</span> lost",
  "<span>Leeds United</span> tied"
 ] 

Finally if you want to get rid of that initial empty string just shift the array once

contentsArray.shift()

CodePudding user response:

Maybe regex is slightly faster? Seems like you indend to get rid of line breaks?

const parentString = '\r\nManchester United won\r\nManchester City lost\r\nLeeds United tied'
const repalcedString = parentString.replace(/(\r\n|\n|\r)/gm, "");
console.log(repalcedString)

  • Related