Mehdi Farhangian Mehdi Farhangian - 4 months ago 8
R Question

Remove a particular character from the end of each string

How can I remove "/" from the end of my data. Let's assume this is my data

#input
ID page
1 www.example.com/, ww.example.com/flight, www.example.com/flight/
2 www.example.com/, ww.example.com/flight


I wish to remove "/" from those who had as their last character and my output will be like that

#output
ID page
1 www.example.com, ww.example.com/flight, www.example.com/flight
2 www.example.com, ww.example.com/flight

Answer

We can use gsub without the lookarounds.. Here, we remove the / followed by either at the end of the string ($) or a , and replace it with ,. In the subsequent sub we remove the , at the end.

df1$page <- sub(",$", "", gsub("/($|,)", ",", df1$page))

df1$page
#[1] "www.example.com, ww.example.com/flight, www.example.com/flight" 
#[2] "www.example.com, ww.example.com/flight"         

Or another option is

 gsub("/(?!\\b)", "", df1$page, perl = TRUE)
 #[1] "www.example.com, ww.example.com/flight, www.example.com/flight" 
 #[2] "www.example.com, ww.example.com/flight"