0

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?

3 Answers 3

3

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

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

Comments

0

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;
});

Comments

0

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.

Comments

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.