Javascript regex replace single slash in to double slash?

◇◆丶佛笑我妖孽 提交于 2019-12-06 11:50:01
yourString.replace(/([^\/])\/([^\/])/g,"$1//$2")

This would work assuming your string does not also end in a /

yourString.replace(/\/[^\/]/g,"//")
  • /stuff/ is just JavaScript regex literal notation
  • \/ is an escaped "/"
  • [^\/] is anything but a "/" (again, with escaping)
  • the "g" on the regex literal means "replace all matches and not just the first"

which we replace for "//" which is what you want.

replace accepts a string and returns a new string with the value changed without changing the original.

Here is a working fiddle

Could be also helpful:

var s = "http://www.some-url.com//path//to";
var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!