简体   繁体   中英

Not able to split by [] and replace string from array

I am trying to replace name with id. I have array of object like:

let obj = [{
id: 123,
name: 'abcd',
},{
id: 234,
name: 'new name',
}];

And I have string.

let str = "[123] Hello how are you? [234] and you? [123] Please call me."

I am trying to replace id [123] with name. But, split not working properly and couldn't find good way to replace all.

I tried.

 let obj = [{ id: 123, name: 'abcd', }, { id: 234, name: 'new name', }]; let str = "[123] Hello how are you? [234] and you? [123] Please call me." let transformedMessage = str.split('[')[0]; //Or even following way don't know how to replace particular Id with name. obj.forEach(val => { str = str.replace(/\[.*?\]\s?/g, val.name) }); console.log(str);

But, it gives blank data.

I am trying to get string like: "abcd Hello how are you? new name and you?"

I think you can loop on your array and replace id occurences with name value.

is something like following works for you?

 function solve(){ let obj = [{ id: 123, name: 'abcd', }, { id: 234, name: 'new name', }]; let str = "[123] Hello how are you? [234] and you?"; obj.forEach(o=> { str = str.replace('['+o.id+']', o.name); }); console.log(str); } solve();

And this is for all occurences

 function solve(){ let obj = [{ id: 123, name: 'abcd', }, { id: 234, name: 'new name', }]; let str = "[123] Hello how are you? [234] and you?"; obj.forEach(o=> { str = str.replace(new RegExp('\\[' +o.id+ '\\]', 'gi'), o.name); }); console.log(str); } solve();

you could use the string-replace function of javascript.

let obj = [{
   id: 123,
   name: 'abcd',
 }, {
   id: 234,
   name: 'new name',
}];
    
let str = "[123] Hello how are you? [234] and you?"
    
obj.forEach(el => {    
    transformedMessage = str.replace('[' + el.id + ']', el.name);
})

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