Javascript beginner: how to replace a href text if it matches a specified string?
When someone posts a link to another page on my website, I'd like to shorten the a href text from someth开发者_如何学JAVAing 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>
str = str.replace(/^http:\/\/www.mywebsite.com/, "");
someElement.appendChild(document.createTextNode(str));
Note that you're introducing a Cross-Site Scripting vulnerability by directly calling document.write
with user input (you could also say you're not treating the URL http://<script>alert('XSS');</script>
correctly).
Instead of using document.write
, replace someElement
in 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 the load
event fires.
精彩评论