代码之家  ›  专栏  ›  技术社区  ›  John Jackson

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

  •  0
  • John Jackson  · 技术社区  · 7 年前

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

    例子:

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

    我怎么能这样做呢?显然最简洁有效的方法是理想的。。。有什么建议吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   CertainPerformance    7 年前

    使用正则表达式:

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

    如果您也希望允许空字符串,那么更改 + (重复小组一次或多次)至 * (重复0组或更多次)。

        2
  •  0
  •   Nick Parsons Felix Kling    7 年前

    另一种方法是 .split 以及 Set 要检查“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;'));

    注:

        3
  •  0
  •   random    7 年前

    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));