0

Quick. I have a string: #user 9#I'm alive! and I want to be about to pull out "user 9".

So far Im doing:

    if(variable.match(/\#/g)){
            console.log(variable):
    }

But the output is still the full line.

JMP
  • 557
  • 1
  • 6
  • 17

2 Answers2

2

Use .split(), in order to pull out your desired item.

var variable = variable.split("#");
console.log(variable[1]);

.split() turns your string into an array, with the first variable as a separator.

Of course, if you just want regex alone, you could do:

console.log(variable.match(/([^#]+)/g));

This will again give you an array of the items, but a smaller one as it doesn't use the empty value before the hash as an item. Further, as stated by @Stephen P, you will need to use a capture group(()) to capture the items you want.

Daedalus
  • 7,586
  • 5
  • 36
  • 61
1

Try something more along these lines...

var thetext="#user 9#I'm alive!";
thetext.match(/\#([^#]+)\#/g);

You want to introduce a capturing group (the part in the parentheses) to collect the text in between the pound signs.

You may want to use .exec() instead of .match() depending on what you're doing. Also see this answer to the SO question "How do you access the matched groups in a javascript regex?"

Community
  • 1
  • 1
Stephen P
  • 14,422
  • 2
  • 43
  • 67