I am working on a project, which using rich text editor that some users typed link without https like this " which is broken the link. I need to find all urls without http:// in href attribute and append a http:// to them, such as " => ".I wrote a function which can find all urls without http:// and a function find a certain patten in a string. However, every time it only changes one url, but not all urls and also return undefined. Does anyone can help? Thank you so much in advanced!
const text = `<h2 class="ql-align-center"><a href="wallacefund.info/" rel="noopener noreferrer" target="_blank" class="ql-size-large">JUMP INTO</a><span class="ql-size-large"><a href="abc.com">abc</a>`;
// try to replace all no http:// url to http://url:
function getReplacedStr (target, source, wantedTarget) {
if (source.length === 0 || target.length === 0 || target.length > source.length) return;
for (let start = 0; start < source.length; start++) {
if (source.charAt(start) === target.charAt(0)) {
let end = start + target.length;
if (end <= source.length && source.substring(start, end) === target) {
return source.replace(target, wantedTarget);
}
}
}
return source;
}
// get an array contains all no http:// urls :
// in this case should return ["wallacefund.info/", "abc.com"]
function getNoHttpUrls (source) {
let regexp = /href="([^\'\"]+)/g;
let res = [...source.matchAll(regexp)], output = '';
const noHttpUrls = res.map(ele => {
if (source.includes(ele[1]) && !ele[1].includes('http')) {
return ele[1];
}
}).filter(e => e);
return noHttpUrls;
}
const output = getNoHttpUrls(text).forEach(target => {
return getReplacedStr(target, text, `http://${target}`);
});