[英]Get first specific special character that occurs in a string
How can I extract the first special character (allowing only #
and .
) from a string? 如何从字符串中提取第一个特殊字符(仅允许
#
和.
)?
For example: 例如:
svg#hello
would return #
svg#hello
将返回#
-hello-world#testing
would return #
-hello-world#testing
将返回#
-hello-world.testing
would return .
-hello-world.testing
将返回.
.test
would return .
.test
将返回.
and so on? 等等?
You can use .match(/[#.]/)
on your strings to match the characters you want: 您可以在字符串上使用
.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] );
If you ever want to extend it to other special chars, you may want to use a reversed regex like .match(/[^a-zA-Z0-9-]/)
on your strings, to match the non letters, non numbers and not -
characters: 如果您想将其扩展为其他特殊字符,则可能要在字符串上使用反向
.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] );
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.