![](/img/trans.png)
[英]string.endswith(“”) does not work in IE(not sure how to use a Polyfill)
[英]How to check for string.endsWith and ignore whitespace
我有此工作功能,以檢查字符串是否以:
結尾
var string = "This is the text:"
function (string) {
if (string.endsWith(':')) {
// ends with :
}
if (string.endsWith(': ')) {
// ends with : and a space
}
else {
// does not end with :
}
}
我還想檢查字符串是否以冒號結尾,后跟空格,甚至兩個空格:_
或:__
(其中下划線表示此語法中的空格)。
關於如何使用多個if語句或定義冒號和空格的每種可能組合的任何想法? 假設冒號后面可以有任意數量的空格,但是如果最后一個可見字符是冒號,我想在函數中捕獲它。
您可以使用String.prototype.trimEnd
從末尾刪除空格,然后檢查:
function (string) {
if (string.endsWith(':')) {
// ends with :
}
else if (string.trimEnd().endsWith(':')) {
// ends with : and white space
}
else {
// does not end with :
}
}
對於您的特定示例,@ Steve的答案將很好地起作用,因為您正在針對字符串末尾的特定條件進行測試。 但是,如果要針對更復雜的字符串進行測試,則還可以考慮使用正則表達式 (也稱為RegEx)。 該Mozilla文檔中有關於如何對JavaScript使用正則表達式的出色教程。
要創建一個正則表達式模式並將其用於測試您的字符串,您可以執行以下操作:
const regex = /:\\s*$/; // All three will output 'true' console.log(regex.test('foo:')); console.log(regex.test('foo: ')); console.log(regex.test('foo: ')); // All three will output 'false' console.log(regex.test('foo')); console.log(regex.test(':foo')); console.log(regex.test(': foo'));
...其中正則表達式/:\\s*$/
可以這樣解釋:
/ Start of regex pattern
: Match a literal colon (:)
\s Right afterward, match a whitespace character
* Match zero or more of the preceding characters (the space character)
$ Match at the end of the string
/ End of regex pattern
您可以使用Regexr.com對您提出的不同正則表達式模式進行實時測試,並且可以在文本框中輸入示例文本以查看您的模式是否匹配。
正則表達式是一個強大的工具。 在某些情況下,您想使用它們,而在某些情況下,它會顯得過大。 對於您的特定示例,僅使用簡單的.endsWith()
更直接,並且最有可能成為首選。 如果您需要執行復雜的模式匹配,而JavaScript函數不會削減它,則正則表達式可以解決問題。 值得一讀,並在工具箱中放置另一個好工具。
您好,您可能想使用正則表達式/(:\\ s *)/
s *將匹配0或所有空格(如果存在)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.