[英]how to write the regex not to allow spaces in the beginning and ending ,but spaces inneed to allow between the words
我們如何允許特殊字符就像其他字符一樣同時不允許開頭和結尾的空格
public addressPattern: string="[a-zA-Z0-9][\\sa-zA-Z0-9]{0,19}";
你可以用這個表達
^\S(?:.*\S)?$
^
- 字符串的開始\\S
- 匹配任何非空格字符(?:.*\\S)?
- 匹配零次或多次后跟非空格字符的任何內容(可選)$
- 字符串結束 let checker = (str) => { return /^\\S(?:.*\\S)?$/.test(str) } console.log(checker('H')) console.log(checker(' H')) console.log(checker('H ')) console.log(checker('Hello friend'))
如果您希望空字符串評估為真,那么您只需添加一個簡單的條件
return str.length === 0 ? true :/^\S(?:.*\S)?$/.test(str)
我用了這么多正則表達式的東西最后這段代碼幫我解決了這個問題
public addressPattern=/^(?:\S.{0,}\S)?$/;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.