Samuel Monteiro
Samuel Monteiro

Reputation: 152

Regex delimit the start of a string and the end

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.

Upvotes: 0

Views: 50

Answers (2)

DexJ
DexJ

Reputation: 1264

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

Upvotes: 0

Hamms
Hamms

Reputation: 5107

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.

Upvotes: 4

Related Questions