When someone posts a link to another page on my website, I’d like to shorten the a href text from something like: http://mywebsite.com/posts/8 to /posts/8 or http://mywebsite.com/tags/8 to /tags/8. Since I’m learning javascript I don’t want to depend on a library like prototype or jquery. Is it recommended to use javascript’s replace method?
I found w3schools’ page here but my code was replacing all instances of the string, not just the href text.
Here’s what I have so far:
<script type="text/javascript" charset="utf-8">
var str="http://www.mywebsite.com";
document.write(str.replace("http://www.", ""));
</script>
Note that you’re introducing a Cross-Site Scripting vulnerability by directly calling
document.writewith user input (you could also say you’re not treating the URLhttp://<script>alert('XSS');</script>correctly).Instead of using
document.write, replacesomeElementin the above code with an element in your code that should contain the user content. Notice that this code can not be at the JavaScript top level, but should instead called when theloadevent fires.