【问题标题】:Replace certain values in a string based on a mapping - JS基于映射替换字符串中的某些值 - JS
【发布时间】:2021-06-01 17:00:48
【问题描述】:

我有一个带有单词的字符串,后跟一个冒号。我需要用对象中的值替换该字符串中的冒号。我能够提取出冒号词,但不确定在字符串中替换它的最佳方式。

这就是我所拥有的:

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

最终结果应该是

This is Alabama button link by Arun

请指教。

【问题讨论】:

标签: javascript regex string


【解决方案1】:

你可以split字符串,然后调用数组map替换单词和join到最终字符串

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

str.split(' ').map(a => {
                         if(a.startsWith(":"))
                           return data[a.replace(":","")]; 
   
                         return a;
                  }).join(' ');

【讨论】:

    【解决方案2】:

    首先,您需要将const buttonName = 'button link'; 移动到数组中。

    您需要使用String#replace,但还需要捕获: 之后的正则表达式部分,并实际使用Group #1 值作为键以获得正确的data 值。

    此外,您需要检查提取的密钥是否在字典中以避免出现问题。

    你可以使用

    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)

    【讨论】:

      【解决方案3】:

      如果您已经从字符串中删除了“:”,则可以迭代您的对象键并将它们替换为相应的值。

      ...
      const res = string.match(/:[a-zA-Z]+/g).map(i => i.replace(':', ''))
      
      for (const [key, value] of Object.entries(data)) {
          res = res.replaceAll(key, value);
      }
      

      【讨论】:

        【解决方案4】:

        Wiktor 的回答很好。但是如果它也需要替换全局变量,我们可以编写如下代码。

        const res = string.replace(/:([a-zA-Z_]+)/g, (m, i) => data[i] ?? eval(i) ?? m);
        console.log(res)
        

        这段代码还没有进行异常处理。应该考虑在内。所以我们可以定义一个replacer函数处理异常

        const replacer = (m, i) => {
            try {
                return data[i] ?? eval(i);
            } catch {
                return m;
            }
        }
        
        const res = string.replace(/:([a-zA-Z_]+)/g, replacer);
        

        【讨论】:

          猜你喜欢
          • 2021-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-05
          • 2018-08-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多