0

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I like your first option, easier to understand.
Glad it helps !
0

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(":");

2 Comments

Thank you, this looks like it would work, but I would prefer regex if possible.
A regex answer may be just as (or more) complex than this. Why regex in particular?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.