compress()
函数将接受一个句子并返回一个删除了所有空格和标点符号的字符串。
此函数必须调用isWhiteSpace()
和isPunct()
。
我已经完成了要调用的函数,但我不知道我的 js 代码中缺少什么才能调用这些函数。
function compress(sent) {
var punc = "; : . , ? ! - '' "" () {}";
var space = " ";
if (punc.test(param)) {
return true
} else {
return false
}
if (space.test(param)) {
return true
} else {
return false
}
isWhiteSpace(x);
isPunct(x);
}
最佳答案
This function must call isWhiteSpace() and isPunct().
所以你已经有了两个函数,我假设当传递的字符是空格或标点符号时返回 true
。那么您不需要也不应该通过在代码中为空格和标点符号实现基于正则表达式的重复文本来复制此功能。保持干燥 - 不要重复自己。
基于这两个函数的 compress
函数如下所示:
function isWhiteSpace(char) {
return " \t\n".includes(char);
}
function isPunct(char) {
return ";:.,?!-'\"(){}".includes(char);
}
function compress(string) {
return string
.split("")
.filter(char => !isWhiteSpace(char) && !isPunct(char))
.join("");
}
console.log(compress("Hi! How are you?"));
我同意正则表达式测试可能是现实世界场景中的首选:
function compress(string) {
return string.match(/\w/g).join("");
}
但是,您特别要求调用 isWhiteSpace
和 isPunct
的解决方案。
关于javascript - 从字符串中删除标点符号和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123869/