简体   繁体   中英

String replace a url with part of the same url in javascript

I have string that contains a random url:

http://google.com/vocab/prefix#Billy

That needs to be transformed so that everything up to, and including the first # is replaced with the value between the last / and the first # followed by a : .

The result would be:

prefix:Billy

More examples:

http://some.url/a/path#elephant --> path:elephant
http://random.com/cool/black/beans/thing#Bob --> thing:bob

I understand how to capture the prefix part /([^\\/]+(?=#))/ , but I'm struggling to do a string replace because I can't figure out how to capture the part I need to replace.

myString.replace(/([^\/]+(?=#))/, '$1:')

I would prefer to use string.replace with regex if at all possible

When using replace method you need to match all the patterns you want to replace instead of just the part you need to keep; Here are two options:

 let s = 'http://google.com/vocab/prefix#Billy' // using greedy regex console.log(s.replace(/.*\\/([^#]+)#/, '$1:')) // adapted from OP's attempt console.log(s.replace(/.*?([^\\/]+?)#/, '$1:')) 

Note .* part to match the substring you want to discard, () to capture the pattern you want to keep, then reformat the output.

Try this code:

var myString = "http://google.com/vocab/prefix#Billy";
var hashIndex = myString.indexOf("#"); // find where the "#" is

for(var i = hashIndex; i > 0; i--) { // loop from "#" index *back* to closest "/" symbol
  if(myString[i] == "/") break; // break loop when "/" is found
}

myString = myString.replace("#", ":"); // replace "#" with ":" as in your example

console.log(myString.substring(i, hashIndex); // output 

Shortened:

var myString = "http://google.com/vocab/prefix#Billy".replace("#",":");
for(var i = myString.indexOf(":"); i > 0; i--) { if(myString[i] == "/") break; }
console.log(myString.substring(i, myString.indexOf(":");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM