最近,我在JavaScript(節點)上面臨一個問題。基本上,我有一個字串(它可以是任何東西,因為它是由用戶輸入的),我必須檢查:
- 如果字串的字母都是小寫的;
- 如果該字串沒有任何特殊字符(é-[?*$,等等(這只是一個例子);
- 如果該字串有任何特殊字符。
- 如果該字串沒有數字;
- 如果該字串有一個以上的單詞,在所有單詞之間只有一個空白/空白。僅此而已,別無他求。
我知道這可能太多,但我沒有其他選擇,只能尋求幫助,因為我不是使用RegEx的專家。
PS:我最接近的方法是使用這個:
const regexPattern = string.match(/^[^a-z] $/) ? false : true;
但這只對一個詞有效,僅此而已。如果有一個以上的單詞,它將不會對其他單詞做任何處理,而我需要的是檢查每個單詞,并檢查它們之間是否只有一個空白。
謝謝! 我真的很感激!
uj5u.com熱心網友回復:
這是一個非重碼的解決方案
。你可以用空格分割字串,并使用Array.every來檢查字串中的每個詞是否與重碼匹配。
另外,你的重碼應該是/^[a-z] $/。洗掉^,因為它顛倒了條件。
function validate(str){
return str.split(" ") 。 every(e => /^[a-z] $/.test(e))
}
console.log(validate("hello world"/span>)
console.log(validate("hello"/span>)
console.log(validate("hello world"))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
這里是一個有效的重合詞。/^([a-z] |([a-z] [a-z] ) )$/
。
const regexPattern = /^([a-z] |([a-z] [a-z] ) )$/>
console.log(regexPattern.test('this should work') // true>
console.log(regexPattern.test('thisshouldwork') //true
console.log(regexPattern.test('this should not work') //假的。
console.log(regexPattern.test('thisshouldnotwork ')) //假的。
console.log(regexPattern.test('$% this should not work') //假的。
console.log(regexPattern.test(') // false
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321031.html
標籤:
