I want to test if a string ONLY contains specific substrings (as whole words) / spaces
I've written some code and it works, but I am concerned that I don't understand the regex (I've copied from elsewhere)
Is there a way of doing this without complex regex?
const str1 = 'a♭ apple a a a a a apple a♭ a'; // valid
const str2 = 'a♭ apple a a a a a apple a♭ aa'; // invalid aa
const str3 = 'a♭ apple ad a a a apple a♭ a'; // invalid ad
const str4 = ' a♭ apple a a a a a apple a♭ a'; // valid
const str5 = ' a♭ apple a a a a a apple a♭ a '; // valid
const str6 = 'a♭ apple a a a a a apple a♭ a '; // valid
const str7 = ' '; // invalid
const str8 = ''; // invalid
const allowedSubstrings = [
'a', 'a♭', 'apple'
]
const isStringValid = str => {
if (str.trim() === '') return false
allowedSubstrings.forEach(sub => {
// https://stackoverflow.com/a/6713427/1205871
// regex for whole words only
const strRegex = `(?<!\\S)${sub}(?!\\S)`
const regex = new RegExp(strRegex, 'g')
str = str.replace(regex, '')
})
str = str.replaceAll(' ', '')
// console.log(str)
return str === ''
}
console.log('str1', isStringValid(str1))
console.log('str2', isStringValid(str2))
console.log('str3', isStringValid(str3))
console.log('str4', isStringValid(str4))
console.log('str5', isStringValid(str5))
console.log('str6', isStringValid(str6))
console.log('str7', isStringValid(str7))
console.log('str8', isStringValid(str8))
((?![apple|a|a♭| ]).)*done onregexr.com