如何在Array.prototype.replace方法内的for循环中迭代正确?

时间:2017-09-21 14:36:25

标签: javascript arrays regex object replace

我正在使用regex和replace方法转换字符串。脚本检查缩写数组中是否存在缩写,如果该单词少于三个字符长。这是在String.prototype.replace() method内的回调中完成的。

我认为问题出在for...in statement

我收到此字符串:"BLABLABLALBLA COOL DOG",但如果for in方法应该正常工作,它应返回"BLABLABLALBLA CAT COOL DOG CAT" ...



    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);
        for (abbreviation in abbreviations) {
          if (abbreviations.hasOwnProperty(abbreviation)) {
            if (match === abbreviations[abbreviation].abbreviation) {
              console.log("match YES!");
              console.log("match", match);
              console.log(
                "abbreviation in the object: ",
                abbreviations[abbreviation].abbreviation
              );
              return abbreviations[abbreviation].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);




0 个答案:

没有答案