views:

96

answers:

2

I would like to extract some text between two points in a string, in Javascript

Say the string is

"start-extractThis-234"

The numbers at the end can be any number, but the hyphens are always present.

Ideally I think capturing between the two hypens should be ok.

I would like the result of the regex to be

extractThis
+2  A: 

why not just do

var toExtract = "start-extractThis-234";
var extracted = null;
var split = toExtract.split("-");
if(split.length === 3){
   extracted = split[1];
}
mkoryak
+1 for this. As long as the string format will always be like this then `split` is a much better choice than a regex match. `if` statement might be a bit overkill though, `extracted = split[1];` or `if (extracted = split[1])` should be enough for most situations.
Andy E
yeah the if is a bit overkill, i wanted to be verbose
mkoryak
Accepted due to simplicity, I was hoping to learn a bit of funky Regex but I can't turn down readability. I shouldn't have been making this complicated!
optician
@optician: don't worry, you'll get your chance at learning some funky regex sooner or later ;-)
Andy E
A: 
^.+?-(.+?)-\d+$
SilentGhost
I will asses if this works, and if so vote it up, as it is the correct answer! I was hoping to be able to choose the split points, so this may be helpful.
optician