【问题标题】:How to I return the correct value from the callback within a String.prototype.replace() method?如何从 String.prototype.replace() 方法中的回调返回正确的值?
【发布时间】:2017-09-21 22:31:59
【问题描述】:

我有这段代码,它应该返回"BLABLABLALBLA CAT COOL DOG CAT",但现在它返回"BLABLABLALBLA C COOL D P C"...

代码中的错误在String.prototype.replace()方法的回调中。

目前我只是返回match,这是由替换方法过滤的值。在回调中,我想检查 abbreviations 的数组中是否存在 D、P 或 C,如果存在,则脚本应打印缩写,否则不应打印任何内容,因为我不想显示任何少于 3 个字符的单词,如果它们不存在于缩写数组中。

replace() 方法的回调应该为 d 返回 dog,为 c 返回 cat,对于 p 应该只返回一个空字符串 (""),因为 p 在 abbreviations 数组中不存在。

请查看附件代码:

const abbreviations = [
      { abbreviation: "d", expansion: "dog" },
      { abbreviation: "c", expansion: "cat" },
      { abbreviation: "h", expansion: "horse" }
    ];
    
    const testStringOriginal = "      blablablalbla,  / c  coOL @ d p  233c    ";
    
    const filterPattern1 = /[^a-zA-Z]+/g; // find all non English alphabetic characters.
    const filterPattern2 = /\b[a-zA-Z]{1,2}\b/g; // find words that are less then three characters long.
    const filterPattern3 = /\s\s+/g; // find multiple whitespace, tabs, newlines, etc.
    
    const filteredString = testStringOriginal
      .replace(filterPattern1, " ")
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
      .replace(filterPattern2, match => {
        console.log("typeof: ", typeof match);
        abbreviations.forEach( item => {
          if (abbreviations.hasOwnProperty(item)) {
            if (match === item.abbreviation) {
              console.log("match YES!");
              console.log("match", match);
              console.log(
                "abbreviation in the object: ",
                item.abbreviation
              );
              return item.expansion; // return DOG, CAT or HORSE (if any match)
            } else {
              console.log("match - NO!");
              return "";
            }
          }
        });
        return match;
      })
      .replace(filterPattern3, " ")
      .trim() // remove leading and trailing whitespace.
      .toUpperCase(); // change string to upper case.
    console.log("ORGINAL STRING:" + testStringOriginal);
    console.log("CONVERTED STRING:" + filteredString);

【问题讨论】:

    标签: javascript arrays regex string foreach


    【解决方案1】:

    您从错误的函数(forEach 回调)返回替换。您需要让forEach 更新一个外部变量,然后返回它,或者干脆使用.find 来做同样的事情:

    const abbreviations = [
        {abbreviation: "d", expansion: "dog"},
        {abbreviation: "c", expansion: "cat"},
        {abbreviation: "h", expansion: "horse"}
    ];
    
    const testStringOriginal = "      blablablalbla,  / c  coOL @ d p  233c    ";
    
    const filteredString = testStringOriginal
        .replace(/\b\w{1,3}\b/g, match => {
            let abbr = abbreviations.find(x => x.abbreviation === match);
            return abbr ? abbr.expansion : '';
        });
    
    console.log("CONVERTED STRING:" + filteredString);

    【讨论】:

    • @georg 你这个人!我会用完整的代码更新帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多