Y.M.P
Y.M.P

Reputation: 3

Replace the string between 2 specific occurances of characters

http://everyone.abc.com/systems/practices/xyz/Untitled.png

In above string, 'http://everyone.abc.com/systems/practices/' this part is constant and '/Untitled.png' part can be anything and want to change string between these 2 parts i.e 'xyz' to 'abc'

Basically wants to replace the string between 5th and 6th occurrence of character '/'.

Upvotes: 0

Views: 86

Answers (2)

Farhan
Farhan

Reputation: 1483

Try this. Find postion of 5th occurrence and then 6th. Cut string till 5th and concatenate required text then concatenate reaming part

var test = "http://everyone.abc.com/systems/practices/xyz/Untitled.png";

var fifth,sixth;
var pos = 5;
var matchText = "/";

fifth = findPos(pos,test,matchText);
pos = 6;
sixth = findPos(pos,test,matchText);

function findPos(pos,test,matchText){
 var counter = 0;
  for (var i=1; i<=test.length; i++){
    if(test.charAt(i) === matchText){
      counter++;
      if(counter == pos){
      return i;
      }

    }
  }
}

var str = test.substring(0,fifth+1)+"custoome text"+test.slice(-(test.length-sixth));
console.log(str);

Demo https://jsfiddle.net/farhanbaloch/cnwa1uv3/

Upvotes: 1

amespower
amespower

Reputation: 917

How about this:

var url = "http://everyone.abc.com/systems/practices/xyz/Untitled.png";
newUrl = url.replace('xyz', 'abc');
console.log(newUrl);

Upvotes: 0

Related Questions