I have a piece of code, which goal is to replace every occurence of @something with an anchor tag. The replacement itself works fine, the looping in general does not. Just consider this a string manipulation method, which has to find every occurence of something, then replace it with something else - but can't do replace all, since it depends on what comes after the '@' character.
Here is the code.
private generateAnchors(content: string) {
let cutIndex = 0;
let contentToReturn = content;
let leftToAnalyze = content;
if (leftToAnalyze.indexOf('@') !== -1) {
while (true) {
leftToAnalyze = content.substring(cutIndex);
leftToAnalyze = leftToAnalyze.substring(content.indexOf('@'));
let tag = leftToAnalyze.substring(leftToAnalyze.indexOf('@'), leftToAnalyze.indexOf(' ', leftToAnalyze.indexOf('@')));
cutIndex += leftToAnalyze.indexOf(tag)+tag.length;
let address = tag.substring(1, tag.length);
let anchor = '<a href="/home/user/'+address+'">'+tag+'</a>';
let newContentSubString = leftToAnalyze.replace(tag, anchor);
contentToReturn = contentToReturn.replace(leftToAnalyze, newContentSubString);
if (leftToAnalyze.indexOf('@') === -1) break;
}
}
return contentToReturn;
}
in a small string like ' hello @JEDS & @Mill also @theHulk deserves a mention' it works fine. However I found an occurrence with was a larger string, where the @ tag was in the end of the string, and it seemed like it was looping forever, and replacing stuff it weren't supposed too.
What am I overseeing in this piece of code?