Mert Çelik
Mert Çelik

Reputation: 382

Javascript regular expression selecting multiple

my problem is selected expressions cant use more than one but i need it

here i prepare a example of what i want

var regexp = /(^| )([a-z]{1})( |$)/gim;

var string = "h ello e x a mple";

var choosen = string.match(regexp);

for(var i = 0; i < choosen.length; i++){
    console.log(choosen[i]);
}

you can see this only chooses "h ", " e ", " a "

but i want to choose "h", "e", "x", "a" without any " "

i know i can do it without regexp but this is really important for me

Upvotes: 2

Views: 541

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

In your case, you may simply try matching all groups consisting of non separator characters:

var input = "h ello e x ample";
var matches = [];
var regexp = /\b[^\s]\b/g;
match = regexp.exec(input);
while (match != null) {
    matches.push(match[0]);
    match = regexp.exec(input);
}

console.log(matches);

The regex pattern \b[^\s]\b seeks to match any single non whitespace character which is also bounded on both sides by word boundaries. In this case, it translates to matching the single letters (though it could also match other things, depending on a different input).

Upvotes: 2

Related Questions