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

问题描述 投票:0回答:3

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

例:

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

我怎么能这样做?显然,最简洁有效的方法是理想的...任何建议?

javascript string detection html-entities
3个回答
1
投票

使用正则表达式:

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

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


0
投票

另一种方法是使用.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;'));

注意:这也会获取空格


0
投票

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));
© www.soinside.com 2019 - 2024. All rights reserved.