[英]Javascript: Get index of first special regex character in a string
[英]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.