[英]Regex to allow only two words, one space and limit to 50 characters
我正在嘗試使用以下條件構建正則表達式:
喜歡(“姓氏姓氏”)
謝謝。
嘗試這個:
const validate = data => /^\\w+\\s*\\w+ ?$/.test(data) && data.length <= 50 const testData = ['this works', 'this too ', ' this fails', 'firstname lastname ', ' firstname middlename lastname '] for (let temp of testData) { console.log(`${temp} ${validate(temp)}`) }
這是一個正則表達式,涵蓋了您的所有要求,包括長度檢查:
^(?!.{51,})(\w+\s+\w+ ?)$
說明:
^(?!.{51,}) assert that the string is not followed by 51 or more characters
(
\w+ match a word
\s+ followed by one or more spaces
\w+ followed by a second word
? ending with an optional space
)$
function tests(str){ var regex = /^(?!.{51,})(\\w+\\s+\\w+ ?)$/; if (regex.test(str)) { console.log("passes"); } else { console.log("fails"); } } tests("firstname lastname "); // passes tests("first name last name"); // fails tests("123456789 1234567890123456789012345678901234567890"); // passes (length 50) tests("123456789 12345678901234567890123456789012345678901"); // fails (length 51)
function tests(str){ var pat=/^[a-zA-Z]+\\s[a-zA-Z]+\\s?$/; if(pat.test(str) && str.length<=50){ console.log("true"); } else{ console.log("false"); } } tests("firstname lastname "); //true tests("first name last name"); //flase
您可以通過將字符串分成這樣的數組來檢查字數
var array = "some string".split(" "); //result - ["some","string"]
現在您可以檢查字數
var count = array.length; //will return 2
你可以像這樣數字母
var letterCount = "some string".length; //will return 11
比使用正則表達式更輕松,更好。
此模式將幫助/^[aZ]+\\s[aZ]+\\s?$/
<input type="text" pattern="^[a-Z]+\s[a-Z]+\s?$" title="Must be two words...">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.