【问题标题】:Why is string.replace() not working inside the function when it works perfectly outside of it? [duplicate]为什么 string.replace() 在函数外部完美运行时却无法在函数内部运行? [复制]
【发布时间】:2022-11-20 08:01:11
【问题描述】:

我正在尝试使用此函数将给定字符串中的“...”替换为存储在数组中的其他不同字符串:

`

function addTokens(input, tokens) 
{
  let returnInput = input;

  if ((typeof input === 'string') || (input instanceof String)) 
  { 
      if(input.length >= 6)
      {
          for (let i = 0; i < tokens.length; i++) 
          {
              if((tokens[i].tokenName === 'string') || (tokens[i].tokenName instanceof String))
              {
                  returnInput = returnInput.replace("...",`${tokens[i].tokenName}`);
              }   
              else
              {
                  //throw new Error("Invalid array format");
              }
          }
      }
      else
      {
          //throw new Error("Input should have at least 6 characters"); 
      } 
  }
  else
  {
      //throw new Error("Input should be a string");
  } 

  return returnInput;
}

`

我什至对错误进行了评论,以便它们不会以任何方式进行干扰,但它似乎不起作用; 如果我打电话

result = addTokens('User ...', [{ tokenName: 'user' }])
console.log(result)

,它只返回初始的“User ...”而不是我想要的“User ${user}”。

但是,当我运行这段代码时:

`

let str = "User ...";
let tok = [{ tokenName: "user" }]
str = str.replace("...", `${tok[0].tokenName}`);
console.log(str);

`

就其本身而言,它完全符合我的预期。

谁能帮我找出问题所在?对于任何新手错误,我深表歉意,我是 Javascript 的新手。谢谢!

【问题讨论】:

  • 您的 if 语句永远不会为真。 "user" instanceof String是false不是true

标签: javascript string replace


【解决方案1】:

"" instanceof String 返回false,因为String 是围绕string 原语的包装类。如果你真的想检查它是string还是String,你可以这样做

(typeof str === "string" || str instanceof String)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2020-05-04
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多