簡體   English   中英

獲取出現在字符串中的第一個特定特殊字符

[英]Get first specific special character that occurs in a string

如何從字符串中提取第一個特殊字符(僅允許#. )?

例如:

svg#hello將返回#

-hello-world#testing將返回#

-hello-world.testing將返回.

.test將返回.

等等?

您可以在字符串上使用.match(/[#.]/)來匹配所需的字符:

 var texts = ['svg#hello', '-hello-world#testing', '-hello-world.testing', '.test']; var regex = '[#.]'; // You need to add the [0] to get the element of the array returned by the function console.log( texts[0].match(regex)[0], texts[1].match(regex)[0], texts[2].match(regex)[0], texts[3].match(regex)[0] ); 


如果您想將其擴展為其他特殊字符,則可能要在字符串上使用反向.match(/[^a-zA-Z0-9-]/)正則表達式,例如.match(/[^a-zA-Z0-9-]/) ,以匹配非字母,非數字而不是-字符:

 var texts = ['svg#hello', '-hello-world#testing', '-hello-world.testing', '.test', '_new-test']; var regex = '[^a-zA-Z0-9-]'; // You need to add the [0] to get the element of the array returned by the function console.log( texts[0].match(regex)[0], texts[1].match(regex)[0], texts[2].match(regex)[0], texts[3].match(regex)[0], texts[4].match(regex)[0] ); 

希望能幫助到你。

暫無
暫無

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

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