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 it is not very efficient
Is there a more efficient way of doing this?
Here’s my inefficient code
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 allowedSubstrings = [
'a', 'a♭', 'apple'
]
const isStringValid = str => {
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))
2
Answers
One approach which I can think of(which avoids complex
regex
) would be to:words
array(created by above split) is included in theallowedSubstrings
array.A single regular expression pattern that checks whether the string contains only the specified substrings as whole words or spaces. It uses the
join('|')
method to create an alternation pattern (|
) for the allowed substrings and then tests the string against this pattern usingtest()
.