CPC
CPC

Reputation: 181

How to test if certain characters are in certain part of string in Javascript

I have a string, just a completely random example could be

",hello, other, person, my, name, is, Caleb,"

It will have lots of commas. I want to check to make sure that there is the letter "a", "m" or "h" between every two commas, and if there isn't, I want to get rid of that whole section of words, so that that string would become:

",hello, other, my, name, Caleb,"

Is there any way I can do that?

Upvotes: 0

Views: 46

Answers (3)

p.s.w.g
p.s.w.g

Reputation: 148980

You can use the filter method (introduced in ES5, so it may not be available in older browsers). For example:

var input = ",hello, other, person, my, name, is, Caleb,";

var output = input
    .split(',')                         // explode string into array
    .filter(function(s) {               // only permit strings for which the following expression is true
        return !s.length ||             // allow empty strings (at beginning and end)
               /[ahm]/.test(s); })      // allow strings with an a, h, or m.
    .join();                            // convert string back to array

Here's another solution using only regular expressions:

var output = "," + input.match(/([^,]*[ahm][^,]*)/g).join() + ",";

The pattern matches any sequence of characters between commas which contains an a, h, or m.

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276276

You can use .filter , .join and .split :

var str = ",hello, other, person, my, name, is, Caleb,";
str.split(","). // split on ,
    filter(function(el){ 
         return /[amh]/.test(el); // test against the letters a m or h
    }).
    join(","); // add the commas back, might need to do "," since the first string is ""

So in short:

",hello, other, person, my, name, is, Caleb,".split(",").filter(function(el){ return /[amh]/.test(el);})

Note that these methods all return the result rather than changing anything in place (for strings this is of course no surprise since they're immutable (fixed) anyway). So you have to assign the output somewhere

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

Split the string into parts:

var parts = str.split(",");

Check each word:

var newArray = parts.filter(function(i) {
    return i.indexOf("a") > -1 && i.indexOf("m") > -1 && i.indexOf("h") > -1;
});

Upvotes: 0

Related Questions