Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace certain values in a string based on a mapping - JS

I have a string with words followed by a colon. I need to replace the colon words in that string with values from an object. I was able to extract out the colon words but not sure on the best way to replace it in the string.

This is what I have:

const string = 'This is :state :buttonName by :name';

const buttonName = 'button link';

const data = {
  state: 'Alabama',
  name: 'Arun'
}

const res = string.match(/:[a-zA-Z]+/g).map(i => i.replace(':', ''))


console.log(res)

// This is Alabama button link by Arun

End result should be

This is Alabama button link by Arun

Please advice.

like image 650
a2441918 Avatar asked Dec 06 '25 05:12

a2441918


2 Answers

First of all, you need to move const buttonName = 'button link'; to the array.

You need to use String#replace, but also you need to capture the part of the regex after : and actually use the Group #1 value as key to get the right data value.

Besides, you need to check if the extracted key is inside the dictionary to avoid issues.

You can use

const string = 'This is :state :buttonName by :name';
const data = {
  buttonName: 'button link',
  state: 'Alabama',
  name: 'Arun'
}
const res = string.replace(/:([a-zA-Z]+)/g, (m, i) => i in data ? data[i] : m)
console.log(res)
like image 64
Wiktor Stribiżew Avatar answered Dec 07 '25 17:12

Wiktor Stribiżew


You can split the string and then call array map to replace words and the join to final string

const str= 'This is :state :buttonName by :name';

str.split(' ').map(a => {
                         if(a.startsWith(":"))
                           return data[a.replace(":","")]; 
   
                         return a;
                  }).join(' ');
like image 21
Vivek Bani Avatar answered Dec 07 '25 17:12

Vivek Bani