简体   繁体   English

获取出现在字符串中的第一个特定特殊字符

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM