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ś?
//https://stackoverflow.com/a/52544985/17318538
const convertLinks = ( input ) => {
let text = input;
const linksFound = text.match( /(?:www|https?)[^\s]+/g );
const aLink = [];
if ( linksFound != null ) {
for ( let i=0; i<linksFound.length; i++ ) {
let replace = linksFound[i];
if ( !( linksFound[i].match( /(http(s?)):\/\// ) ) ) { replace = 'http://' + linksFound[i] }
let linkText = replace.split( '/' )[2];
if ( linkText.substring( 0, 3 ) == 'www' ) { linkText = linkText.replace( 'www.', '' ) }
if ( linkText.match( /youtu/ ) ) {
let youtubeID = replace.split( '/' ).slice(-1)[0];
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>' )
}
else if ( linkText.match( /vimeo/ ) ) {
let vimeoID = replace.split( '/' ).slice(-1)[0];
aLink.push( '
<div class="video-wrapper"><iframe src="https://player.vimeo.com/video/' + vimeoID + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>' )
}
else {
aLink.push( '
<a href="' + replace + '" target="_blank">' + linkText + '
</a>' );
}
text = text.split( linksFound[i] ).map(item => { return aLink[i].includes('iframe') ? item.trim() : item } ).join( aLink[i] );
}
return text;
}
else {
return input;
}
}
const text = document.getElementById("test-text").innerHTML
document.getElementById('converter-result').innerHTML = convertLinks( text )
rozwiązania tego typu nie działają...:
const text = document.getElementsByClassName("test-text").innerHTML
document.getElementsByClassName('post').innerHTML = convertLinks( text )
const text = document.getElementById("test-text").innerHTML
document.querySelectorAll('.post').innerHTML = convertLinks( text )
const text = document.querySelectorAll(".post").innerHTML = convertLinks( text )
Ten post edytował phpuser88 22.12.2022, 08:09:12