2

I want to select the character from matched text, but not sure how to do the lookbehind select.

For example, I want to select out the "a" from the "apple" only, and not from "pineapple", I used the regex below:

/\ba(?=pple)/gi

I want to select the "e" from "apple" only, but not sure how to write the regex. The below regex will return the whole word "apple", instead of "e" only.

/\b(appl)e/gi

How can I select out the "e" or any other character such as "l" ?

var text = "apple pineapple aeroplane";

var lookahead = /\ba(?=pple)/gi;
alert(text.match(lookahead));

var lookbehind = /\b(appl)e/gi;
alert(text.match(lookbehind));

4
  • Your first example works doesn't it? Only a is alerted. Commented Dec 8, 2015 at 4:38
  • How about this, jsfiddle.net/pks9xLfe? Commented Dec 8, 2015 at 4:45
  • /\b(a)pple/ likewise: /\bappl(e)/ if you what's the purpose of Matching Group () Selecting the characters like you do makes me wander what you're actually up to. Commented Dec 8, 2015 at 4:57
  • @chris85, I'm trying to not using the matched[2], as I need to have a long regex, and this is part of it only. Commented Dec 8, 2015 at 6:07

1 Answer 1

1

You could do it easily with lookbehind but unfortunately it's not supported by javascript. What you can do instead is to use group capturing and to only retrieve the portion you are insterested in e.g. to capture only "e" of "apple" you could write something like:

var matched = /\bappl(e)/.exec('apple');
var capturedChar = null;
if (matched) {
   // [0] contains the whole matched string, "apple", and [1] contains "e"
   capturedChar = matched[1]; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Actually I need a very long regex that contains multiple conditions, and this is only part of it. So I'm trying not to use matched[1].
Well, if you could provide a more complete explanation and examples of your situation we would be able to help you better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.