首页 > 解决方案 > Javascript 检查字符串是否仅包含 nbsp;

问题描述

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

例子:

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

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

标签: javascriptstringdetectionhtml-entities

解决方案


使用正则表达式:

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

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


推荐阅读