JQuery using Regex to find links in text, but exclude if link is in quotes

I am using jQuery and Regex to search for a text string for http or https and convert the string to url. I need some code to skip a line if it starts with a quote.

below is my code:

// Get the content
var str = jQuery(this).html();

// Set the regex string
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

var replaced_text = str.replace(exp, function(url) {
    clean_url = url.replace(/https?:\/\//gi,'');
    return '<a href="' + url + '">' + clean_url + '</a>';
})

jQuery(this).html(replaced_text);

      

Here's an example of my problem:

Text The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter <a href="https://twitter.com/abcdef">@Abcdef</a>.

The current code successfully finds text that starts with http or https and converts it to a URL, but also converts the Twitter URL. I need to ignore text if it starts with a quote or is in a tag, etc.

Any help is greatly appreciated

+3


source to share


2 answers


How about adding [^"']

to a variable exp

?

var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

      

Excerpt:



// Get the content
var str = jQuery("#text2replace").html();

// Set the regex string
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

var replaced_text = str.replace(exp, function(url) {
    clean_url = url.replace(/https?:\/\//gi,'');
    return '<a href="' + url + '">' + clean_url + '</a>';
})

jQuery("#text2replace").html(replaced_text);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="text2replace">
The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter <a href="https://twitter.com/abcdef">@Abcdef</a>.
</div>
      

Run codeHide result


+2


source


If you really just want to ignore the quotes, this might help:



var replaced_text = $("#selector").html().replace(/([^"])(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '$1<a href="$2">$2</a>');

      

0


source







All Articles