Hirad Roshandel
Hirad Roshandel

Reputation: 2187

Extract substrings from a string with a certain character

I'm trying to extract all substrings that start with ! for a string in Javascript. for example if my string is:

Hi Jack !Smile, This is a !silly text to try out this !Code!

So the output should be an array with elements:

var arr = ['Smile', 'Silly', 'Code']

The reason I'm doing is because I want to convert these codes into emoticons for my chatroom and "!" is an indicator that this is an emoticon code. Is there any fast and optimal to do this and not go through every word using a for loop?

Upvotes: 0

Views: 62

Answers (2)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can use the following regex

!(.+?)\b

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388326

I think a simple regex along with an array processing should do it

var string = "Hi Jack !Smile, This is a !silly text to try out this !Code!";

var match = string.match(/!(.+?)\b/g),
  array = match ? match.map(function(val) {
    return val.substring(1)
  }) : [];

snippet.log(JSON.stringify(array))
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 3

Related Questions