我有这段代码,它应该返回“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/