Znalazłem kompleksowe rozwiązanie zmiany tekstu w formie linków na linki klikalne <a href>.
Problem w tym że gotowiec dokonuje transformacji tekstu z określonego <div id> do określonego <div id>, a mi zależy na tym żeby przerobić go do obsługi <div class="post"> i nie bardzo wiem jak to zrobić. Próbowałem na kilka różnych sposobów, ale JS nigdy nie był dla mnie zbyt zrozumiały... pomoże ktoś?
  1. //https://stackoverflow.com/a/52544985/17318538
  2. const convertLinks = ( input ) => {
  3.  
  4. let text = input;
  5. const linksFound = text.match( /(?:www|https?)[^\s]+/g );
  6. const aLink = [];
  7.  
  8. if ( linksFound != null ) {
  9.  
  10. for ( let i=0; i<linksFound.length; i++ ) {
  11. let replace = linksFound[i];
  12. if ( !( linksFound[i].match( /(http(s?)):\/\// ) ) ) { replace = 'http://' + linksFound[i] }
  13. let linkText = replace.split( '/' )[2];
  14. if ( linkText.substring( 0, 3 ) == 'www' ) { linkText = linkText.replace( 'www.', '' ) }
  15. if ( linkText.match( /youtu/ ) ) {
  16.  
  17. let youtubeID = replace.split( '/' ).slice(-1)[0];
  18. aLink.push( '<div class="video-wrapper"><iframe src="https://www.youtube.com/embed/' + youtubeID + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>' )
  19. }
  20. else if ( linkText.match( /vimeo/ ) ) {
  21. let vimeoID = replace.split( '/' ).slice(-1)[0];
  22. aLink.push( '<div class="video-wrapper"><iframe src="https://player.vimeo.com/video/' + vimeoID + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>' )
  23. }
  24. else {
  25. aLink.push( '<a href="' + replace + '" target="_blank">' + linkText + '</a>' );
  26. }
  27. text = text.split( linksFound[i] ).map(item => { return aLink[i].includes('iframe') ? item.trim() : item } ).join( aLink[i] );
  28. }
  29. return text;
  30.  
  31. }
  32. else {
  33. return input;
  34. }
  35. }
  36.  
  37. const text = document.getElementById("test-text").innerHTML
  38. document.getElementById('converter-result').innerHTML = convertLinks( text )


rozwiązania tego typu nie działają...:
  1. const text = document.getElementsByClassName("test-text").innerHTML
  2. document.getElementsByClassName('post').innerHTML = convertLinks( text )
  3.  
  4. const text = document.getElementById("test-text").innerHTML
  5. document.querySelectorAll('.post').innerHTML = convertLinks( text )
  6.  
  7. const text = document.querySelectorAll(".post").innerHTML = convertLinks( text )