JSFiddle - React, Tailwind, and code Playground

by Ken Z

HTML

<div id="phrase">
    I tweeted something #one #two @three @four
</div>

<p>
    <a href="javascript:void(0);" class="replaceone">Replace all atsign I see</a>
</p>

<p>
    <a href="javascript:void(0);" class="replaceall">Replace all hashtags in the string</a>
</p>

<p>
    <a href="javascript:void(0);" class="reset">Reset to the original, unmodified string</a>
</p>

CSS

.hashtag {
    background-color: red;
    color: #FFFFFF;
    padding: 0px 2px;
}

.atsign {
    background-color: green;
    color: #FFFFFF;
    padding: 0px 2px;
}

JavaScript

var status = 'I tweeted something #one #two @three @four';

$('.replaceone').click(function(e) {
    e.preventDefault();
    var newStatus = status.replace(/@([^ ]+)/g, '<span class="atsign">@$1</span>');
    $("#phrase").html(newStatus);
});

$('.replaceall').click(function(e) {
    e.preventDefault();
    var newStatus = status.replace(/#([^ ]+)/g, '<span class="hashtag">#$1</span>');
    $("#phrase").html(newStatus);
});

$('.reset').click(function(e) {
    e.preventDefault();
    $("#phrase").html(status);
});