Ramesh
Ramesh

Reputation: 1887

Javascript regex replace single slash in to double slash?

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&

Upvotes: 2

Views: 4796

Answers (3)

Burak Tasci
Burak Tasci

Reputation: 907

Could be also helpful:

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

Upvotes: 0

Khanh TO
Khanh TO

Reputation: 48972

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

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276276

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

Upvotes: 1

Related Questions