Search code examples
javascriptstringdetectionhtml-entities

Javascript check if string contains only nbsp;


This may be extremely trivial but I'm looking for a way to check if a string contains ONLY the html entity nbsp;

Example:

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

How can I go about doing so? obviously the most concise efficient method would be ideal... any suggestions?


Solution

  • Use a regular expression:

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

    If you want to permit the empty string as well, then change the + (repeat the group one or more times) to * (repeat the group zero or more times).