dsp_099
dsp_099

Reputation: 6121

How to match between characters but not include them in the result

Say I have a string "&something=variable&something_else=var2"

I want to match between &something= and &, so I'll write a regular expression that looks like:

/(&something=).*?(&)/

And the result of .match() will be an array:

["&something=variable&", "&something=", "&"]

I've always solved this by just replacing the start and end elements manually but is there a way to not include them in the match results at all?

Upvotes: 0

Views: 475

Answers (3)

mrak
mrak

Reputation: 504

If you are trying to get variable out of the string, using replace with backreferences will get you what you want:

"&something=variable&something_else=var2".replace(/^.*&something=(.*?)&.*$/, '$1')

gives you

"variable"

Upvotes: -1

Chris Cherry
Chris Cherry

Reputation: 28554

You can't avoid them showing up in your match results at all, but you can change how they show up and make it more useful for you.

If you change your match pattern to /&something=(.+?)&/ then using your test string of "&something=variable&something_else=var2" the match result array is ["&something=variable&", "variable"]

The first element is always the entire match, but the second one, will be the captured portion from the parentheses, which is much more useful, generally.

I hope this helps.

Upvotes: 1

nickb
nickb

Reputation: 59699

You're using the wrong capturing groups. You should be using this:

/&something=(.*?)&/

This means that instead of capturing the stuff you don't want (the delimiters), you capture what you do want (the data).

Upvotes: 2

Related Questions