I am trying to limit the number of URLs someone can add to a textarea. I have a regex that can find all the URLs just fine. Here is the issue I'm running into:
When two links are right next to each other, but separated by a space, the code I've written will not identify the second link. If I separate them by two spaces, then they will be identified. I have no idea what is going on here.
function limitLinks() {
var counter = 0;
var url = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/?)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\)){0,}(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s\!()\[\]{};:\'\"\.\,<>?«»“”‘’]){0,})/ig;
var sig = $(".textarea").val();
var sigsplit = sig.replace(/\n/g, " ").split(" ");
var links = [];
for (var i = 0; i < sigsplit.length; i++) {
if (url.test(sigsplit[i])) {
counter++;
links.push(sigsplit[i]);
}
}
console.log("Here's the split text:" + sigsplit);
console.log("All the links are:" + links);
}
limitLinks();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<textarea class="textarea">foo.com bar.com</textarea>
</form>
With one space separating the URLs, it only identifies the first link. If you add a space to separate the URLs by two spaces, it identifies both. I don't think the regex is the problem here - the regex will find both URLs just fine. It has something to do with the array that is created, I think, when I split the textarea value by spaces.
Any insight would be really appreciated... I've spent too much time trying to figure this out!