0

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

2 Answers 2

5

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, ... ];
Sign up to request clarification or add additional context in comments.

1 Comment

Woah, I was under the impression that /^,\s/ within the array and not bound by quotes would break the array. Should have tested it first. Thanks.
3

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.

2 Comments

Typo sorry! meant ^,\s. Part of the reason I don't like using the array, is because you can easily misplace your commas. Single regex rocks!
@ThomasReggi: Put spaces between your commas, makes it a lot more legible

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.