Me Unagi
Me Unagi

Reputation: 625

Find and replace between second and third slash

I have urls with following formats ...

/category1/1rwr23/item
/category2/3werwe4/item
/category3/123wewe23/item
/category4/132werw3/item
/category5/12werw33/item

I would replace the category numbers with {id} for further processing.

/category1/{id}/item

How do i replace category numbers with {id}. I have spend last 4 hours with out proper conclusion.

Upvotes: 1

Views: 638

Answers (2)

Saleem
Saleem

Reputation: 8978

Assuming you'll be running regex in JavaScript, your regex will be.

/^(\/.*?\/)([^/]+)/gm

and replacement string should look like $1whatever

var str = "your url strings ..."

var replStr = 'replacement'; 

var re = /^(\/.*?\/)([^/]+)/gm;

var result = str.replace(re, '$1'+replStr);

console.log(result);

based on your input, it should print.

/category1/replacement/item
/category2/replacement/item
/category3/replacement/item
/category4/replacement/item
/category5/replacement/item

See DEMO

Upvotes: 2

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34150

We devide it into 3 groups 1.part before replacement 2.replacement 3.part after replacement

yourString.replace(//([^/]*\/[^/]+\/)([^/]+)(\/[^/]+)/g,'$1' + replacement+ '$3');

Here is the demo: https://jsfiddle.net/9sL1qj87/

Upvotes: 0

Related Questions