Javascript: Replacing chan-like replies within a string
-
14-06-2021 - |
Question
I am here because I need help solving this problem. So I have this string (for example). Oh and obviously the >>
are displayed as >>.
Lorem ipsum dolor sit amet >>21, consetetur sadipscin>>22g elitr.
>>11 I agree.
>>61 Lorem ipsumdur. See >>36
What I want to do now is: replace the
>>INTEGER
with the following:
<a href="javascript:void(0);" onclick="scroll(INTEGER)">>>INTEGER</a>
Solution
Try this :
yourString.replace(/>>[0-9]+/g,'firstPart'+'$&'+'secondPart');
Refer javascript replace method for more details. Where "$&" , Inserts the matched substring. So the final code would be :
yourString.replace(/>>[0-9]+/g,'<a href="javascript:void(0);" onclick="alert($1);">'+'$&'+'<\/a>');
OTHER TIPS
You just call a replace in scroll function.
ej
var stringToReplace = 'Lorem ipsum dolor sit amet >>21, consetetur sadipscin>>22g elitr......',
textReplaced = ' your new value here';
function scroll(integer){
return stringToReplace.replace(new RegExp('>>'+integer,'g'),textReplaced);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow