Gsub match specific string and replace with blank

I am trying to replace a specific string using gsub but it's not working correctly.

Input -> /ICW/PDR/backend
Desired Output -> /ICW/PDR

What I have used is,

gsub => ["backend_name", "[\/backend]", ""]

However, it ends up creating this

Output -> ICWPDR

Can someone please help?

The 2nd argument to gsub is a Regular Expression.


To remove the last slash and everything that follows it in a sequence, the following pattern should work:

  gsub => ["backend_name", "/[^/]*$", ""]

Explained:

  • /: a literal forward slash,
  • [^/]*: followed by a sequence of zero or more characters that are not forward slashes,
  • $: followed by the end-of-line

If what follows the backslash is always exactly backend, this may be a little more performant:

  gsub => ["backend_name", "/backend$", ""]

Explained:

  • /backend: a literal forward slash followed by the sequence b a c k e n d,
  • $: followed by the end-of-line
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.