JS Regex combining

I have such string with requirements to exclude anything except

a-zA-Z0-9,

special characters

()+-.,‘?/:

Also double or more slashes should be restricted And string should not start and end with slash.

Example:

var str = "///a/ab*/*/bc:dD:123a///'Ad/,.?/!//";

//if I use js replace with regex rule twice I get needed result

"///a/ab*/*/bc:dD:123a///'Ad,.?/!//"
   .replace(/[^0-9a-zA-Z()+-.,‘?/:]/g, "")
   .replace(/[^\/+|\/+$|\/{2,}]/g, "");

//result 
"a/abbc:dD:123aAd/,.?"

**Is it possible to combine these rules into one regex rule?!**

//tried to combine these rules by '|' but get failure result

"///a/ab*/*/bc:dD:123a///'Ad/,.?/!//"
   .replace(/([^0-9a-zA-Z()+-.,‘?/:])|^\/+|\/+$|\/{2,}/g, "")
//result
"a/ab//bc:dD:123aAd/,.?/"

1 answer

  • answered 2018-07-18 11:30 Wiktor Stribiżew

    You may use

    var str = "///a/ab*/*/bc:dD:123a///'Ad/,.?/!//";
    var na = "[^0-9a-zA-Z()+.,‘?/:-]+";
    var reg = new RegExp("/+$|^/+|(^|[^/])/(?:" + na + "/)*/+$|/{2,}|/(?:" + na + "/(?!/))+|" + na, "g");
    console.log(str.replace(reg, "$1"));

    Details

    • /+$ - 1+ / chars at the end of the string
    • | - or
    • ^/+ - matches 1+ / at the start of the string
    • | - or
    • (^|[^/])/(?:[^0-9a-zA-Z()+.,‘?/:-]+/)*/+$ - a start of string or any non-/ char (captured into $1) followed with / followed with 1 or more repetitions of 1+ chars other than the sets/ranges in the character class and a / not followed with another / and then 1+ / at the end of the string
    • | - or
    • /{2,} - any 2 or more slashes
    • | - or
    • /(?:[^0-9a-zA-Z()+.,‘?/:-]+/(?!/))+ - a / followed with 1 or more repetitions of 1+ chars other than the sets/ranges in the character class and a / not followed with another /
    • | - or
    • [^0-9a-zA-Z()+.,‘?/:-]+ - 1+ chars other than the sets/ranges in the character class

    See the regex demo online.