Javascript 检查字符串是否只包含 nbsp;

Javascript check if string contains only nbsp;

这可能非常微不足道,但我正在寻找一种方法来检查字符串是否仅包含 html 实体 nbsp;

示例:

// checking if string ONLY CONTAINS nbsp;
'nbsp;' -> true
'nbsp;nbsp;nbsp;nbsp;' -> true
'nbsp;nbsp; HELLO WORLD nbsp;' -> false

我该怎么做呢?显然最简洁有效的方法是理想的...有什么建议吗?

使用正则表达式:

const test = str => console.log(/^(?:nbsp;)+$/.test(str));
test('nbsp;');
test('nbsp;nbsp;nbsp;nbsp;');
test('nbsp;nbsp; HELLO WORLD nbsp;');

如果您也想允许空字符串,则将 +(重复该组一次或多次)更改为 *(重复该组零次或多次)。

另一种方法是使用 .splitSet 来检查 "nbsp;" 是否与其他项目一起出现在您的字符串中:

const check = str => new Set(str.split('nbsp;')).size == 1

console.log(check('nbsp;'));
console.log(check('nbsp;nbsp;nbsp;nbsp;'));
console.log(check('nbsp;nbsp; HELLO WORLD nbsp;'));

注意:这也会提取空格

const input1 = 'nbsp;';
const input2 = 'nbsp;nbsp;nbsp;nbsp;';
const input3 = 'nbsp;nbsp; HELLO WORLD nbsp;';

function allSpaces(str) {
    let arr = str.trim().split(';');
    arr = arr.slice(0, arr.length - 1);
    return arr.every(str => str === 'nbsp');
}

console.log(allSpaces(input1));
console.log(allSpaces(input2));
console.log(allSpaces(input3));