0

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 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, works perfectly! I was a bit disappointed that you can't do this with the match function..
@Niels Glad it worked. If this solved your problem please mark the green 'very good' sign on the left ;)
yes I'm waiting for the stupid 4 minutes i have to wait before I can accept your answer. What is this delay for...
@Niels Maybe it allows other people to submit their answers which might be better than the ones already provided.
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.