2

I'm trying to trim the values of an href before and after the domain name using JavaScript. For example, http://www.google.com/about-us should be trimmed to www.google.com.

var str = "http://www.google.com/about-us";
var str_before = str.replace("http://","");
document.write(str_before); // Returns ("www.google.com/about-us")

// Trim everything after the domain name

var link = str_before.substring(0, str_before.indexOf('/'));
document.write(link); // Returns "www.google.com/about-uswww.google.com"

I don't know why this is happening. Any help would be greatly appreciated!

4
  • var a = document.createElement("a"); a.href = str; a.host; // "www.google.com" Commented Dec 29, 2016 at 17:23
  • 1
    Nope, it's document.write tricking you. Use console.log to check the results of your code. Commented Dec 29, 2016 at 17:23
  • 2
    do not use document.write, forget it exists. Why do beginner courses teach people to use it, it is not the 90/00s any more. Commented Dec 29, 2016 at 17:26
  • @epascarello Not only some courses, but even MDN examples often use dw(). I've left feedback for Mozilla a couple of years ago about using dw() in examples, but not sure, if its use has been decreased. Commented Dec 30, 2016 at 12:44

1 Answer 1

2

You are seeing the output of the previous document.write concatenated with the output of the second document.write. If you add a line break to the output, you will see the real output as two lines and you will see that the result is in fact correct.

Try the code snippet below:

var str = "http://www.google.com/about-us";
var str_before = str.replace("http://","");
document.write(str_before); // Outputs "www.google.com/about-us"

// Trim everything after the domain name
var link = str_before.substring(0, str_before.indexOf('/'));

//add line break to the output
document.write( '<br />' );

//output the resulting link
document.write( link );

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

1 Comment

Thanks! I was overlooking the document.write() line I had in place.

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.