I'm currently developing a tool that tags alphanumeric words based on the option selected from the right-click context menu. However, I am facing issues when a group of words containing special characters is selected.
I have been using the following RegEx that I came across on this very site: /(\s[a-zA-Z0-9]+)/g
To demonstrate the problem, try selecting 123b @#$@#$
or @#$@#$ a
from the text, and then right-click and choose an option. The expected outcome should be [TAG] 123b @#$@#$
or @#$@#$ [TAG] a
respectively.
There is also an issue when trying to tag the entire string:
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71031019041d31161c10181d5f121e1c">[email protected]</a> 123a % / ! @$# % % %^* && ^ Lorem ipsum
The expected output should be:
[TAG] <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01736069746d41666c60686d2f626e6c">[email protected]</a> [TAG] 123a % / ! @$# % % %^* && ^ [TAG] Lorem [TAG] ipsum
.
The goal is to tag strings like 123abc
, abc123
, 12ab3
- regardless of the number of digits and letters. Additionally, if an email address is selected, it should also be tagged.
Any suggestions on how to resolve this issue?
HTML:
<p contenteditable="true"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dba9bab3aeb79bbcb6bab2b7f5b8b4b6">[email protected]</a> 123a % / ! @$# % % %^* && ^ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer augue tortor, dictum a turpis non, dapibus vehicula neque. 123b @#$@#$ a quam vel cursus. Duis at mattis quam, ornare consequat enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer augue tortor, dictum a turpis non, dapibus vehicula neque. Aliquam dictum a quam vel cursus. Duis at mattis quam, ornare consequat enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>
JS:
function replaceText(selectedText, selectedTag){
if(selectedText == "")
return false;
if(selectedText.match(/^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/))
replacedText = selectedText.replace(/(\s[a-zA-Z0-9]+)/g, " " + selectedTag + " " + "$1");
else
replacedText = selectedTag + " " + selectedText.replace(/(\s[a-zA-Z0-9]+)/g, " " + selectedTag + " " + "$1");
originalText = $('p').html();
newText = originalText.replace( new RegExp(selectedText,"g") , replacedText);
$('p').html(newText);
}