Output Javascript Array into DIV

1802 views javascript
0

I have function, which shows / should output the urls (it should just list the urls) from the textarea. At the moment however it only shows me the last result / url. How can I output all the arrays / urls (maybe into a div).

My Code:

<textarea id="textarea"></textarea>

<div id="converted_url"></div>

<script type="text/javascript">
$("#textarea").on("change keyup paste", function() {
    var text=document.getElementById("textarea").value;
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    text.replace(urlRegex, function(url) {
    var link = '<div><a href="' + url + '">' + url + '</a></div>';
    document.getElementById("converted_url").innerHTML=link
    })
});
</script>

Output At the Moment (With this code):

Output

Wished (Should be):

enter image description here

answered question

Your .replace() callback allways completely overwrites the <div> content.

But it isn't overwriting as much as i know. It's just outputting the last url...

Do you know how I can get all urls?

Clear out the <div> before calling .replace(), and instead of updating .innerHTML accumulate the URLs in a string. Then after .replace() set .innerHTML to the string.

I'm sorry but I don't get it... Could you send me the code?

1 Answer

6

Whenever you update the result area, you are overwriting the previous results. You need to append to it.

let result = $("#converted_url");

$("#textarea").on("input", function() {
    var text=document.getElementById("textarea").value;
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    text.replace(urlRegex, function(url) {
     var link = '<div><a href="' + url + '">' + url + '</a></div>';
     
     // Append the new information to the existing information
     result.append(link);
    });
});
textarea { width:200px; height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>

<div id="converted_url"></div>

posted this

Have an answer?

JD

Please login first before posting an answer.