【问题标题】:if string contains object key then replace with corresponding value jquery如果字符串包含对象键,则替换为相应的值 jquery
【发布时间】:2020-07-29 22:56:59
【问题描述】:

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

我的字符串:

"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"

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

【问题讨论】:

    标签: javascript jquery object replace key-value


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        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]);
          }
        });
        

        【讨论】:

          猜你喜欢
          • 2022-08-08
          • 2016-04-09
          • 2020-07-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多