sarah
sarah

Reputation: 37

Regex to store only one matching element found in a string-js

I may be asking a stupid Quest, but I'd really like to know if there is there a regular expression to get only the first matched letter from a string?Eg:

var string = "abcdaeee";
var value = 'a';

the value and the string field is dynamic hence they could vary. In above case I'm willing to get only the first matching letter found to the var 'value' (which is 'a') in the string.I currently have this regex:

regex = new RegExp("(" + value + ")", "i"); 
string.match(regex)

instead can i have something like: o/p: a,a

string.match(someValidRegex)// to o/p: a

but this ones gets all the matching a's from the string. Is there a way in regex to display only the first occurrence of a matching element? Eg o/p: ["a"]

Thanks!

Upvotes: 2

Views: 215

Answers (2)

A. L
A. L

Reputation: 12649

Alternatively, if possible, you could use two regexes. One to extract the string, then the other to parse the extracted string to get your character or whatever.

var str = "blah blah blah something blah blah blah";

var matched = str.match(/something/);
var character_matched = matched[0].match(/e/);

the variable character_matched should now contain your letter. You can alter 'something' in the var matched line and 'e' in the var character_matched line to suit your needs. However, my question is: what are you extracting just the character in a particular word/string for?

Also, if you're matching a regex more than once, check if you have globals on.


Alternatively:

var str = "hello";
var letter = "p";
var exists = str.search(letter);
if (exists != -1)
{
    # character is in the string, do something
}
else
{
    # character not in string, do something else
}

Upvotes: 0

Eoghan_Mulcahy
Eoghan_Mulcahy

Reputation: 85

Apologies this is the solution for the first matched letter not using regex

If you just want to get the first matched letter of a string i think that regex is a bit overkill.

This would work

    function getFirstMatchedLetter(str,letter){
        var letterPosition = str.search(letter);
        return str.charAt(letterPosition);
    }

    getFirstMatchedLetter("hello","l");

Upvotes: 1

Related Questions