I want to detect https in a text and make it clickable. How can I do that with RegEx?
const urlRegex = /(https?:\/\/[^\s]+)/g;
return jsonString.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
const html = clickLink(value);
The above code returns value not defined error. I figure it is because const html is defined outside the return call. Any ideas on how i can restructure this? Is there a way for me to do this regEx expression inside the showPhoto function?
This is the full code(which is reproducible). I already have something working with the line if(key ==value), but I want to do it differently with regEX.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="'wrap">
<button class = B1 id="photos">View photos</button>
</div>
<div id="showResults"></div>
</div>
<script>
const showPhoto = (key, value) => {
const pre_x = document.createElement("pre");
const dt_x = document.createElement("dt");
const dd_x = document.createElement("dd")
dt_x.textContent = key;
pre_x.appendChild(dt_x);
if (key == "url") {
const hyperLink = document.createElement("a");
hyperLink.textContent = value;
hyperLink.setAttribute("href", "#");
hyperLink.addEventListener("click", function (e) {
getPhotos(e.target.innerHTML);
});
dd_x.appendChild(hyperLink);
} else {
dd_x.textContent = value;
}
pre_x.appendChild(dd_x);
return pre_x;
};
const clickLink = (value) => {
const urlRegex = /(https?:\/\/[^\s]+)/g;
return jsonString.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
const html = clickLink(value);
const structurePhotos = (obj) => {
const dl = document.createElement("dl");
for (let k in obj) {
let j = obj[k];
if (typeof obj[k] === "object") {
j = JSON.stringify(obj[k], null, 2);
}
dl.appendChild(showPhoto(k, j));
}
return dl;
};
function getPhotos(url) {
fetch(url)
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
.then((data) => {
if (Array.isArray(data)) {
data.forEach((photo) => {
showResults.append(
structurePhotos(photo, 0),
);
});
}
})
.catch(console.error);
}
const photos = document.getElementById("photos");
photos.addEventListener(
"onclick",
getPhotos(`https://jsonplaceholder.typicode.com/photos`)
);
</script>
</body>
</html>