eugene
eugene

Reputation: 41745

Replace regex match in JavaScript

For a given URL,

/disconnect/<backend>/foo/<association_id>/

I'd like to get

/disconnect/:backend/foo/:association_id/

There could be any number of <pattern>s in a path.

Upvotes: 1

Views: 59

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

What about this way? Live Demo http://jsfiddle.net/d4N9s/

var mystring = "/disconnect/<backend>/foo/<association_id>/"
var middle = mystring.replace(/>/g , "")
console.log(middle.replace(/</g , ":"));

Cleaner way:

var mapO = {
   '>':"",
   '<':":",
};
str = mystring.replace(/<|>/gi, function(matched){
  return mapO[matched];
});

console.log(str);

Upvotes: 1

Eric
Eric

Reputation: 169

/<(.*?)>/g

That will match all instances of a string between < and >. You can use some simple JavaScript to replace each instance pretty easily.

http://regexr.com/3ggen

Upvotes: 0

MaxZoom
MaxZoom

Reputation: 7753

Below is a regex to use with replace method

var str = '/disconnect/<backend>/foo/<association_id>/',
    reg = /<([^>]+)>/g;

console.log(str.replace(reg, ":$1"));

DEMO

Upvotes: 1

Related Questions