我想测试一个字符串是否只包含特定的子字符串(作为整个单词)/空格
我已经写了一些代码,它的工作,但我担心它不是很有效
有没有更有效的方法来做到这一点?
下面是我的低效代码
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条答案
按热度按时间zmeyuzjn1#
我能想到的一种方法(避免复杂的
regex
)是:1.基于一个或多个空白字符(空格、制表符或其他)拆分字符串
1.检查
words
数组中的每个字(由上述拆分创建)是否包含在allowedSubstrings
数组中。字符串
fumotvh32#
一个正则表达式模式,用于检查字符串是否只包含指定的子字符串作为整个单词或空格。它使用
join('|')
方法为允许的子字符串创建交替模式(|
),然后使用test()
根据此模式测试字符串。字符串