[英]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.