ThomasReggi
ThomasReggi

Reputation: 59365

Javascript regex pattern array with loop

I have attempted to create a function that will replace multiple regular expression values from an array. This works if the array does not contain quotation marks of any kind, this is problematic when I want to use a comma in my pattern. So I've been trying to find an alternative way of serving the pattern with no luck. Any ideas?

function removeCharacters(str){
    //ucpa = unwanted character pattern array
    //var ucpa = [/{/g,/}/g,/--/g,/---/g,/-/g,/^.\s/];
    var ucpa = ["/{/","/}/","/--/","/---/","/-/","/^.\s/","/^,\s/"];
    for (var i = 0; i < ucpa.length; i++){ 
        //does not work
        var pattern = new RegExp(ucpa[i],"g");
        var str = str.replace(pattern, " ");
    }
    return str;
}

WORKING:

function removeCharacters(str){
    //ucpa = unwanted character pattern array
    var ucpa = [/{/g,/}/g,/--/g,/---/g,/-/g,/^.\s/,/^,\s/];
    for (var i = 0; i < ucpa.length; i++){
        var str = str.replace(ucpa[i], " ");
    }
    return str;
}

REFINED:

function removeCharacters(str){
    var pattern = /[{}]|-{1,3}|^[.,]\s/g;
    str = str.replace(pattern, " ");
    return str;
}

Upvotes: 0

Views: 2484

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

You can also wrap all that into a single regex:

var str = str.replace(/[{}]|-{1,3}|^[.,]\s/g, " ")

although I'm not sure if that's exactly what you want since some of your regexes are nonsensical, for example ,^\s could never match.

Upvotes: 3

SLaks
SLaks

Reputation: 887451

The RegExp constructor takes raw expressions, not wrapped in / characters. Therefore, all of your regexes contain two /s each, which isn't what you want.

Instead, you should make an array of actual regex literals:

var ucpa = [ /.../g, /",\/.../g, ... ];

Upvotes: 5

Related Questions