如果字符串包含对象键,则替换为相应的值 jquery

if string contains object key then replace with corresponding value jquery

我有一个包含一些关键字的字符串,我希望能够用我的对象中的值替换它们。

我的字符串:

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

我希望能够用我的对象中的值替换 {start_date}{end_date}

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

我希望我的声明是:

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

我还需要它是动态的,对象可以改变,字符串可以不同。我不知道该怎么做。

您可以连接管道 (|) 上的所有键以创建正则表达式并使用 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);

您也可以匹配所有包含在花括号中的单词字符,如果对象中存在则替换它。

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);

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);

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]);
  }
});