从字符串中删除标点符号和空格

Kim*_*les 1 javascript

该函数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);
}
Run Code Online (Sandbox Code Playgroud)

le_*_*e_m 5

该函数必须调用 isWhiteSpace() 和 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?"));
Run Code Online (Sandbox Code Playgroud)

我同意正则表达式测试可能是现实世界场景中的最佳选择:

function compress(string) {
  return string.match(/\w/g).join("");
}
Run Code Online (Sandbox Code Playgroud)

但是,您特别要求一个调用isWhiteSpace和的解决方案isPunct