Home > Mobile >  Regex replace last part of url path if condition matches?
Regex replace last part of url path if condition matches?

Time:09-09

I am basically trying to remove the last part of a URL if the URL contains the path /ice/flag/. Example:

Input:

https://test.com/plants/ice/flag/237468372912873

Desired Output:

Because the above URL has /ice/flag/ in its path, I want the last part of the URL to be replaced with redacted.

https://test.com/plants/ice/flag/redacted

However, if the URL did not have /ice/flag (ex: https://test.com/plants/not_ice/flag/237468372912873), it shouldn't be replaced.


What I tried to do is to use the answer mentioned here to change the last part of the path:

var url = 'https://test.com/plants/ice/flag/237468372912873'
url = url.replace(/\/[^\/]*$/, '/redacted')

This works in doing the replacement, but I am unsure how to modify this so that it only matches if /ice/flag is in the path. I tried putting \/ice\/flag in certain parts of the regex to change the behavior to only replace if that is in the string, but nothing has been working. Any tips from those more experienced with regex on how to do this would be greatly appreciated, thank you!


Edit: The URL can be formed in different ways, so there may be other paths before or after /ice/flag/. So all of these are possibilities:

Input:

  • https://test.com/plants/ice/flag/237468372912873
  • https://test.com/plants/extra/ice/flag/237468372912873
  • https://test.com/plants/ice/flag/extra/237468372912873
  • https://test.com/plants/ice/flag/extra/extra/237468372912873

Desired Output:

  • https://test.com/plants/ice/flag/redacted
  • https://test.com/plants/extra/ice/flag/redacted
  • https://test.com/plants/ice/flag/extra/redacted
  • https://test.com/plants/ice/flag/extra/extra/redacted

CodePudding user response:

You may search for this regex:

(\/ice\/flag\/(?:.*\/)?)[^\/] $

and replace it with:

$1redacted

RegEx Demo

Code:

var arr = [
    'https://test.com/plants/ice/flag/237468372912873', 
    'https://test.com/plants/ice/flag/a/b/237468372912873',
    'https://test.com/plants/not_ice/flag/237468372912873'];

var rx = /(\/ice\/flag\/(?:.*\/)?)[^\/] $/m;
var subst = '$1redacted';

arr.forEach(el => console.log(el.replace(rx, subst)));

CodePudding user response:

You can add a ternary operation condition to check if the url includes /ice/flag by url.includes('/ice/flag'), then replace url.replace(/\/[^\/]*$/, '/redacted') else return the url as it is.

function replace(url) {
  return url.includes('/ice/flag') ? url.replace(/\/[^\/]*$/, '/redacted') : url;
}

console.log(replace("https://test.com/plants/ice/flag/237468372912873"))
console.log(replace("https://test.com/plants/not_ice/flag/237468372912873"));

  • Related