简体   繁体   中英

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 #

-hello-world#testing would return #

-hello-world.testing would return .

.test would return .

and so on?

You can use .match(/[#.]/) on your strings to match the characters you want:

 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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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