【问题标题】:How do find substrings and then replace them with returns of a method in javascript?如何找到子字符串,然后用 javascript 中方法的返回替换它们?
【发布时间】:2019-07-21 09:59:50
【问题描述】:

我有一段文字如下:

var txt = 'my name is: {name} {family}'

现在我想通过正则表达式找到{name}{family},然后调用方法。方法如下:

function method(type} {
   if(type === 'name')
      return 'Ali'
   if(type === 'family')
      return 'Malvandi'
}

换句话说,我想找到以{ 开头并以} 结尾的子字符串,然后用方法返回的内容替换它们。

我怎样才能用 javascript 做到这一点?

【问题讨论】:

  • 到目前为止你尝试过什么?如果您需要调试帮助,请发布您尝试过但不起作用的代码
  • 修复了吗? {name} 和 {family},这个字符串会一直在输入中吗?

标签: javascript regex string typescript replace


【解决方案1】:

使用正则表达式提取每对花括号的内容,通过使用replace 的回调参数对捕获的字符调用method

var txt = 'my name is: {name} {family}';

function method(type) {
  if (type === 'name')
    return 'Ali'
  if (type === 'family')
    return 'Malvandi'
}

const res = txt.replace(/\{(.*?)\}/g, (m, r) => method(r));

console.log(res);

如果你使用一个对象,用更多的键/值对来扩展它会容易得多:

var txt = 'my name is: {name} {family}';

const replace = {
  name: "Ali",
  family: "Malvandi"
}

function method(type) {
  return replace[type] || "Name";
}

const res = txt.replace(/\{(.*?)\}/g, (m, r) => method(r));

console.log(res);

【讨论】:

    【解决方案2】:

    你可以使用replace方法的回调

    {([^}]+)}
    

    var txt = 'my name is: {name} {family}'
    
    function method(type) {
       if(type === 'name'){
         return 'Ali'
       }
       if(type === 'family'){
          return 'Malvandi'
       }
    }
    
    let final = txt.replace(/{([^}]+)}/g,(m,g1) => method(g1))
    
    console.log(final)

    【讨论】:

    • 我想找到以 { 开头并以 } 结尾的子字符串,然后用方法返回的内容替换它们
    • @MortezaMalvandi 答案是一样的,它是通过{([^}]+)} 找到{} 字符串,然后替换值
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2013-07-27
    相关资源
    最近更新 更多