简体   繁体   中英

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 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>
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.

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