1

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/,.?/"
7
  • Try .replace(/^\/+|\/+$|\/{2,}|[^0-9a-zA-Z()+.,‘?\/:-]+/g, "") Commented Jul 18, 2018 at 10:44
  • Get "a/ab//bc:dD:123aAd/,.?/" Slash at the end, double slashes Commented Jul 18, 2018 at 10:44
  • Yes, but the double backslash appeared because of * removal, they were not consecutive in the first place. Commented Jul 18, 2018 at 10:49
  • That's why I want firstly use [^0-9a-zA-Z()+.,‘?\/:-] than regex for slashes Commented Jul 18, 2018 at 10:50
  • Try .replace(/^\/+|(^|[^\/])\/(?:[^0-9a-zA-Z()+.,‘?\/:-]+\/)*\/+$|\/{2,}|\/(?:[^0-9a-zA-Z()+.,‘?\/:-]+\/(?!\/))+|[^0-9a-zA-Z()+.,‘?\/:-]+/g, "$1"). I get "a/abbc:dD:123aAd/,.?" Commented Jul 18, 2018 at 10:58

1 Answer 1

1

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.

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

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.