I have a string. I want to replace substrings
with in string. For each substring
I have the starting and ending index. Using regex
is out of scope.
So from let str = "I want chicken pizza and cheese pizza from point restaurant";
The expected result would be like this.
I want TYPE1 TYPE4 and TYPE1 pizza from point restaurant
let str = "I want chicken pizza and cheese pizza from point restaurant";
let roles = [{
"start": 7,
"end": 14,
"typeId": "TYPE1",
"type": "toppings",
"text": "chicken"
},
{
"start": 25,
"end": 31,
"typeId": "TYPE1",
"type": "toppings",
"text": "cheese"
},
{
"start": 15,
"end": 20,
"typeId": "TYPE4",
"type": "main ingredient",
"text": "pizza"
}
];
let styledStr = str;
roles.map(r => {
const { start, end, typeId, text } = r;
let strArr = str.split('');
let removeStr = strArr.splice(start, end, typeId);
styledStr = strArr.join('');
console.log(styledStr);
});
Method using start and end - note I sort the roles so we start at the highest position
let str = "I want chicken pizza and cheese pizza from point restaurant";
let roles = [{
"start": 7,
"end": 14,
"typeId": "TYPE1",
"type": "toppings",
"text": "chicken"
},
{
"start": 25,
"end": 31,
"typeId": "TYPE1",
"type": "toppings",
"text": "cheese"
},
{
"start": 15,
"end": 20,
"typeId": "TYPE4",
"type": "main ingredient",
"text": "pizza"
}
];
let styledStr = str;
roles.sort((a,b)=>b.start-a.start)
roles.forEach(r => {
const { start, end, typeId, text } = r;
// Using substring because it is more readable and saves a split
styledStr = styledStr.substring(0,start) + typeId + styledStr.substring(end)
styledStr.slice(start,end,typeId)
});
console.log(styledStr)
Method using text replace
let str = "I want chicken pizza and cheese pizza from point restaurant";
let roles = [{
"start": 7,
"end": 14,
"typeId": "TYPE1",
"type": "toppings",
"text": "chicken"
},
{
"start": 25,
"end": 31,
"typeId": "TYPE1",
"type": "toppings",
"text": "cheese"
},
{
"start": 15,
"end": 20,
"typeId": "TYPE4",
"type": "main ingredient",
"text": "pizza"
}
];
let styledStr = str;
roles.forEach(r => {
const { start, end, typeId, text } = r;
console.log(start,end,text)
styledStr = styledStr.replace(text,typeId)
});
console.log(styledStr)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments