0

i use this javascript code to editing paragraph if it have links the code will make the link active to click by adding html href element

my problem is the result of this code be in one line

i want the paragraph result stay paragraph not 1 line

any idea?

thanks all

var collection = document.getElementsByClassName("Edit_desc");
    for (let i=0; i<collection.length; i++) {
       
            //Regex Expresson to match general URL used frequently.
            var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
            //Creating Regex Object with the Regex Expression
            var regex = new RegExp(expression);
            //Fetch words from the Text Area , array named 'input_text_words' will contain all words separately
            var input_text_words = collection[i].textContent.trim().split(/\s+/);
            var input_text_number_of_words = input_text_words.length;
            //Empty Paragraph Element
            var paragraphElement = "";
            //Traversing the words array
            for(var index = 0 ; index < input_text_number_of_words ; index++){
                //If the word matches the URL regex than print using <a href="url"> </a> so that link may appear.
                if(input_text_words[index].match(regex)){
                    paragraphElement += '<a href="'+input_text_words[index]+'">'+input_text_words[index]+'</a>';
                }
                //Else if the word is not any url , simply print.
                else{
                    paragraphElement += input_text_words[index];
                }

                if(index != input_text_number_of_words-1){
                    paragraphElement += ' ';
                }
            }
            //Finally show the modified text in tha empty paragraph element.
           
            collection[i].innerHTML = paragraphElement;  
        }

1 Answers1

-1

I suppose that your spaces are not caused by html tags like <br/>
So the problem is the splitting you do :

var input_text_words = collection[i].textContent.trim().split(/\s+/);

The ("string1 string2\nstring3").split(/\s+/); expression splittes the string into 3 items. Making you lose the lines part...
As a solution i suggest you use another regex that partially solves the problem

.split(/[^\S\r\n]/g)

witch i got from this guy

But this solution has possible issues, if the linke is at the start of the paragraph or if you can have a link with lines inside it ( done by a text-area for example ) that wont be selected. So be sure to check what do u need exactly and adjust the regex to something that suites you.

Yasser CHENIK
  • 370
  • 1
  • 6
  • 17
  • Hi, i found answer but i dont test it, replace textContent with innerHTML, the first review i think its work, what is your opinion? – league of omar_ Sep 18 '22 at 09:42