nb_nb_nb
nb_nb_nb

Reputation: 1381

if string contains object key then replace with corresponding value jquery

I have a string that contains some keywords and I want to be able to replace them with values from my object.

My string:

"I want to start the trip on {start_date} and return on {end_date}"

I want to be able to replace {start_date} and {end_date} with values from my object:

let obj = {start_date: "2020-01-01", end_date: "2020-07-15"}

I want my statement to be:

"I want to start the trip on 2020-01-01 and return on 2020-07-15"

I also need this to be dynamic, The object can change and the string can be different. I am not sure how to go about this.

Upvotes: 1

Views: 1164

Answers (3)

Talmacel Marian Silviu
Talmacel Marian Silviu

Reputation: 1736

let sentence =
  "I want to start the trip on {start_date} and return on {end_date}";

let obj = { start_date: "2020-01-01", end_date: "2020-07-15" };

Object.keys(obj).forEach((key) => {
  if (sentence.includes(key)) {
    var regex = new RegExp(`{${key}}`, "g");
    sentence = sentence.replace(regex, obj[key]);
  }
});

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89414

You can join all of the keys on a pipe (|) to create a regular expression and make use of the callback to String#replace.

let str = "I want to start the trip on {start_date} and return on {end_date}"
let obj = {start_date: "2020-01-01", end_date: "2020-07-15"};
function escapeRegExp(string) {
  return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
}
let res = str.replace(new RegExp(
Object.keys(obj).map(str=>"{"+escapeRegExp(str)+"}").join("|"), "g"/*global*/), 
   match=>obj[match.slice(1,-1)]/*remove leading '{' and trailing '}'*/);
console.log(res);

You can also match all word characters enclosed in curly braces and replace it if it exists in the object.

let str = "I want to start the trip on {start_date} and return on {end_date}"
let obj = {start_date: "2020-01-01", end_date: "2020-07-15"};
let res = str.replace(/{(\w+)}/g, (_,capture)=>obj.hasOwnProperty(capture)?obj[capture]:capture);
console.log(res);

Upvotes: 1

GirkovArpa
GirkovArpa

Reputation: 4912

const string = 'I want to start the trip on {start_date} and return on {end_date}';
const obj = { start_date: '2020-01-01', end_date: '2020-07-15' };
const result = string.replace(/{\w+}/g, key => obj[key.slice(1, -1)]);

console.log(result);

Upvotes: 2

Related Questions