简体   繁体   中英

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?

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

An alternative way could be to use .split and a Set to check whether "nbsp;" appears in your string with other items:

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

Note: This will pick up whitespaces as well

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM