I have following string and I want to replace the chars between the "[" and "]":
text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] magna"
and the goal is to get:
newText = "Lorem ipsum dolor sit amet, <a href=www.example1.com target="_blank">Link 1</a> sadipscing elitr, sed diam nonumy <a href=www.example2.com target="_blank">Link 2</a> tempor invidunt ut labore et <a href=www.example3.com target="_blank">Link 3</a> magna"
The following code replaces only the first link (link 1) but link 2 & 3 has no effect
const urlTextChain = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
if (urlTextChain) {
const textUrl = urlTextChain.substring(0, urlTextChain.lastIndexOf("|"));
const url = urlTextChain.substring(urlTextChain.indexOf("|") + 1);
const link = "<a href=" + url + " target=" + '"_blank"' + ">" + textUrl + "</a>";
let newText = text.replace(urlTextChain, link);
newText = newText.replace('[', '');
newText = newText.replace("]", '');
return newText;
}
3
Answers
This is a classic case for regular expression. Do this instead:
Will resolve to:
MDN String.prototype.replace
MDN RegExp
You can use
RegExp
for replace.p1
corresponds to the first parenthesis andp2
is the value corresponding to the second parenthesis.You can use the
replaceAll
method, which uses the same semantics as thereplace
method.