【问题标题】:How do I replace %<string> with the parameters如何用参数替换 %<string>
【发布时间】:2022-09-23 15:44:41
【问题描述】:

我收到这样的 API 响应。

{
  \"message\": \"The password needs at least %1 characters. Password should be having %param2 special characters in it. Create a new password and try again.\",
  \"parameters\": [
    \"8\",
    \"param2test\"
  ]
}

在这里,我应该搜索响应中是否有 %[string],如果有,我需要将 %1 替换为参数的第一个数组元素,将 %2 替换为第二个,依此类推。可能有 n 个参数。我如何在 React 中做到这一点?

    标签: javascript


    【解决方案1】:

    const r = {
        "message": "The password needs at least %1 characters. Password should be having %2 special characters in it. Create a new password and try again.",
        "parameters": [
            "8",
            "2"
        ]
    }
    
    const parameterizedString = (...args) => {
        const [str, ...params] = args;
        return str.replace(/%\d+/g, matchedStr => {
            const variableIndex = matchedStr.replace("%", "") - 1;
            return params[variableIndex];
        });
    }
    console.log(parameterizedString(r.message, ...r.parameters))

    【讨论】:

    • 我已经更新了问题,请检查您是否可以回答@reifocs
    【解决方案2】:

    const obj = {
      "message": "The password needs at least %1 characters. Password should be having %2 special characters in it. Create a new password and try again.",
      "parameters": [
        "8",
        "2"
      ]
    };
    
    
    function change({ message, parameters }) {
      let str = message;
    
      message.match(/(%[0-9]+)/g).forEach((item, i) => {
        str = str.replace(item, parameters[i]);
      })
    
      return str;
    }
    
    console.log(change(obj));

    【讨论】:

    • 这个问题是假设我在字符串中有 %1 %2 %100 它仍然匹配数组的第三个元素
    • 它应该是这样的,是不是应该对消息中的任意数量的%[number] 执行此操作。
    【解决方案3】:

    你可以试试这个:

    const obj = {
      "message": "The password needs at least %1 characters. Password should be having %2 special characters in it. Create a new password and try again.",
      "parameters": [
        "8",
        "2"
      ]
    }
    
    const regex = /%\d/g;
    function f(match){
      const m = Number(match.slice(1))
      return obj.parameters[m-1]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      相关资源
      最近更新 更多