1

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
1
  • Wow, I wonder how many of my old questions I'll be embarrised about like this one! Commented Aug 18, 2012 at 10:23

3 Answers 3

4
string = "start-extractThis-234"

console.log( string.match( '-(.*)-' )[1] );

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

Comments

3

why not just do

var toExtract = "start-extractThis-234";
var extracted = null;
var split = toExtract.split("-");
if(split.length === 3){
   extracted = split[1];
}

4 Comments

+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.
yeah the if is a bit overkill, i wanted to be verbose
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: don't worry, you'll get your chance at learning some funky regex sooner or later ;-)
0
^.+?-(.+?)-\d+$

2 Comments

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.
I like this solution better than the other one. But all this is is a regular expression. but which javascript method you use to extract between the two characters?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.