Mystical
Mystical

Reputation: 2783

Regex match text followed by white space or nothing at all

I am trying to format plain text into rich JavaScript text, and here is the part of my code in question that highlights some sample keywords:

var sampleKeywords = '(function|var|throw|return|class)\s';

elem.innerHTML = elem.textContent.replace(new RegExp(sampleKeywords, 'g'), function(val) {
    return `<mark>${val}</mark>`;
});

The code above highlights any of the sample keywords that appear in the text that are accompanied by a space. This is to prevent highlighting input such as function123.

That being said, I would still like to highlight input such as function with nothing following it.

Essentially, I want to highlight any of the sample keywords followed by a space or not followed by anything at all.

How can I achieve this in my regex pattern?

Note: I am aware of the obvious flaws with my code such as highlighting quoted text or not highlighting every available JavaScript keyword, but the code provided above is only abstract; not complete.

Upvotes: 2

Views: 2029

Answers (1)

melpomene
melpomene

Reputation: 85767

A literal translation of your requirements yields (?=\s|$) ("followed by whitespace or the end of the string").

However, you can simply invert your condition: (?!\S) ("not followed by a non-space character")

You might also want to look into \b (word boundary): \bfoo\b matches foo not preceded or followed by a word character (i.e. a letter, digit, or _).

Upvotes: 3

Related Questions