简体   繁体   中英

Use Javascript or Lodash to replace string

Have a situation where I have a string with multiple links strings as below. I need to replace the link with actual links eg : <a href=”http://www.testing.com” target=_blank>http://www.asdfasd.com</a>

Example text:

http://www.testing.com Simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap https://asdfasdf.com

I am using the below function to get indexes of everywhere that the 'http' occurs but wanted to know if there is an easier way.

indexes(comments.Answers, "http");

function indexes(source, find) {
  var result = [];
  for (var i = 0; i < source.length; ++i) {
    // If you want to search case insensitive use 
    // if (source.substring(i, i + find.length).toLowerCase() == find) {
    if (source.substring(i, i + find.length) == find) {
      result.push(i);
    }
  }
 console.log("result ", result);

  return result;
}

Don't roll your own regex, you'll do it wrong. And you won't even realize it's wrong until it's too late. You'll spend hours and days poring over your regex and finally get it working, go out and get drunk, party hard for a while, only for your clients to come back a month later pissed off that you missed some edge case, invalidating all your work and forcing you to start from scratch. Just don't go there.

Use a tried-and-tested library.

The plugin linkify is built specifically for your purpose. They have a test box on the page where you can try it out, it seems to handle your example text perfectly.

If you really want to build the links manually, the library validator.js has a function called isURL which checks if a given string is a URL. You can iterate through your whitespace-delimited words of text and check if each is a URL, and make it a link as necessary.

If you want to explore further options I'd recommend reading the replies to this old post .

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