簡體   English   中英

檢查字符串的結尾(正則表達式)

[英]Check the end of string (regular expression)

我試圖確定一個字符串(第一個參數,str)是否以給定的目標字符串(第二個參數,目標)結尾。 function confirmEnding(str, target) { return /target$/.test(str) }測試字符串confirmEnding("Bastian","n")顯示為假。 我做錯了什么? 我可以使用正則表達式作為函數的參數嗎? ;

如果它總是一個字符串,那么你可以使用String#endsWith

 function checkEnd(str, target) { return str.endsWith(target); } console.log(checkEnd("Bastion", "n"));

如果您想將target轉換為正則表達式,但請注意這不會轉義target中的任何特殊字符。 checkEnd('special)',')')將由於正則表達式無效而失敗:

 function checkEnd(str, target) { return new RegExp(`${target}$`).test(str); } console.log(checkEnd("Bastion", "n"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM