Alex Polo Alex Polo - 1 month ago 7
Javascript Question

Regex in JavaScript

Suppose we don't know how many slashes we could get in a string but we do not want any extra slashes. So if we get this string '/hello/world///////how/are/you//////////////' we should transform it to the form of '/hello/world/how/are/you/'. How to do it with the help of regular expressions in JavaScript?

Answer
'/hello/world///////how/are/you//////////////'.replace(/\/{2,}/g, '/');

This might be an incy wincy bit faster than mkoryak's suggestion, for it will only replace where necessary – i.e., where there's multiple instances of /. I'm sure someone with a better understanding of the nuts and bolts of the JavaScript regular expression engine can weigh in on this one.

UPDATE: I have now profiled mine and mkoryak's solutions using the above string but duplicated hundreds of times, and I can confirm that my solution consistently worked out several milliseconds faster.

Comments