I'm performing domain validation and input masking on a url string, and am trying to strip out both the protocol and the path from the url using a regex replace. Currently, I'm using two replace functions in sequence: one to replace the protocol and then another to remove the first /
and everything following it.
const stripProtocol = val.replace(/(^\w+:|^)\/\//, '');
const stripPath = stripProtocol.replace(/\w\/(.*)/, '');
// http://stackoverflow.com ==> stackoverflow.com
// http://stackoverflow.com/question/ask ==> stackoverflow.co
The first regex works perfectly, but I'm running into two problems. First is that the match regex being assigned to the stripPath
variable is also removing the /w character immediately preceding the first slash. Secondly, this validation is for an input field mask, meaning it get's executed on every keystroke and then replaces the user's input with the stripped down values. Therefore, I can't simply match for the first occurrence of a /
in the second regex, because when the user begins typing a url that starts with a protocol, for example http://
, everything after the protocol slashes will be removed. I tried a variation on the look behind alternative mentioned in this answer, but had no luck.