javascript - 如何从 String.prototype.replace() 方法中的回调返回正确的值?

标签 javascript arrays regex string foreach

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

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

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

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

请查找附加代码:

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);

最佳答案

您从错误的函数(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);

关于javascript - 如何从 String.prototype.replace() 方法中的回调返回正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46354112/

相关文章:

Javascript - PHP 在 JavaScript 上的 Substr() 替代品

javascript - 我可以在 three.js 中隐藏网格的面吗?

php - 如何将这个php slugify函数重写到mysql?

php - 在 jQuery 中从 PHP 打印数组

javascript - jQuery 问题无法检索或设置属性, 'undefined'

javascript - 如何将 Array.prototype.filter 与异步一起使用?

C - 二维数组中的移动顺序以获得最大收集总和

ios - UITableView 第二个和第三个标签不显示单元格中的值

php - 将段落标签中的第一个字母包裹在跨度标签中

c# - 如何从字符串中解析特定的函数名及其参数?