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 #?
2 Answers
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.
4 Comments
Niels
Thanks, works perfectly! I was a bit disappointed that you can't do this with the match function..
npinti
@Niels Glad it worked. If this solved your problem please mark the green 'very good' sign on the left ;)
Niels
yes I'm waiting for the stupid 4 minutes i have to wait before I can accept your answer. What is this delay for...
npinti
@Niels Maybe it allows other people to submit their answers which might be better than the ones already provided.
var result = myString.match(/#\w+/g);
result.forEach(function (word, index, arr){
arr[index] = word.slice(1);
});
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);
}