JSFiddle - React, Tailwind, and code Playground

by Allendar

JavaScript

var my_string = 'Hey @someotheruser this is a tweet about #topic1 and #topic1';

function wrapInSpan(text, className) {
    return '<span class="' + className + '">' + text + '</span>'
}

my_string = my_string.replace(/(^|)(?:#(\w+))|(?:@(\w+))/g, function handleMatch(match) {
    // Initialize the initial counter
	if (window.counter == undefined) {
		window.counter = 0;
	}
	
	// Do something with a certain so-manieth value
    
	
	// Increment the counter
	window.counter++;
	
	console.log(window.counter);
	
	// Return data
    switch (match[0]) {
        case '@' : return wrapInSpan(match, 'mention');
        case '#' : return wrapInSpan(match, 'hash');
        default:
            console.log('Wrong match found: ' + match);
            return '';
            break;
	}
});

// Remove the counter variable
delete window.counter;

console.log(my_string);