Niels
Niels

Reputation: 1330

Storing part of regex using javascript match

I want to find all #tags in a piece of text (using javascript) and use them. The regex myString.match(/#\w+/g) works, but then I also get the #. How can I get only the word without the #?

Upvotes: 0

Views: 101

Answers (2)

Some Guy
Some Guy

Reputation: 16210

var result = myString.match(/#\w+/g);
result.forEach(function (word, index, arr){
    arr[index] = word.slice(1);
});

Demo

Note that I'm using ES5's forEach here. You can easily replace it with a for loop, so it looks like this:

var result = myString.match(/#\w+/g);
for (var i = 0; i < result.length; i++){
    result[i] = result[i].slice(1);
}

Demo without forEach

Docs on forEach

Upvotes: 0

npinti
npinti

Reputation: 52185

You can do something like this:

var code='...';
var patt=/#(\w+)/g;
var result=patt.exec(code);

while (result != null) {
    alert(result[1]);
    result = patt.exec(code);    
}

The ( and ) denote groups. You can then access these groups and see what they contain. See here and here for additional information.

Upvotes: 2

Related Questions