0

I'm been having trouble with regex, which I doesn't understand at all.

I have a string '#anything#that#i#say' and want that the regex detect one word per #, so it will be [#anything, #that, #i, #say]. Need to work with spaces too :(

The closest that I came is [#\w]+, but this only get 1 word and I want separated.

2
  • Mostra teu código completo Commented May 16, 2017 at 0:56
  • you mean spaces before and after '#' sign! right? Commented May 16, 2017 at 5:10

2 Answers 2

4

You're close; [#\w] will match anything that is either a # or a word character. But what you want is to match a single # followed by any number of word characters, like this: #\w+ without the brackets

var str = "#anything#that#i#say";
var regexp = /#\w+/gi;
console.log(str.match(regexp));

It's possible to have this deal with spaces as well, but I'd need to see an example of what you mean to tell you how; there are lots of ways that "need to work with spaces" can be interpreted, and I'd rather not guess.

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

1 Comment

Ohh yes, what I mean with spaces is the spaces between hashtags like "# anything #that" i need this to be only two words, without taking the space between. But your answer already made that. Thanks :) and sorry for the late response.
0
use expression >>  /#\s*(\w+)/g

\s* : to check if zero or more spaces you have between # and word

This will match 4 word in your string '#anything#that#i#say' even your string is containing space between '#anything# that#i# say'

sample to check: http://www.regextester.com/?fam=97638

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.