Javascript regex replace single slash in to double slash?

烂漫一生 提交于 2019-12-12 09:57:59

问题


Javascript regex replace single slash into double slash not for replace double slash in a string?

var tempPath ="//DocumentImages//Invoices//USD//20130425//I27566554 Page- 1.tif&//hercimg/IMAGES/2008/20130411/16192144/16192144-10003.tif&";

Here replace all single slash in to double (//) not to all double slash.

like //DocumentImages//Invoices//USD//20130425//I27566554 Page- 1.tif&//hercimg//IMAGES//2008//20130411//16192144//16192144-10003.tif&


回答1:


yourString.replace(/([^\/])\/([^\/])/g,"$1//$2")



回答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




回答3:


Could be also helpful:

var s = "http://www.some-url.com//path//to";
var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");


来源:https://stackoverflow.com/questions/16711578/javascript-regex-replace-single-slash-in-to-double-slash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!