【发布时间】: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