I'm trying to write a function which would Uppercase some words in a textarea
but I'm having trouble, as these words could be part of other words and I only want to uppercase them when they are standing alone.
E.g.: I want to uppercase OR
but only when not in a word like befORe
. These words can however be written in a multitude of ways, like at the start of a line, between one or more whitespace
characters or in something like this: (somethingsomething)OR(somethingelse)
and probably even more, depending on the way other people write their query code.
I had the idea of working with regex
, but I'm not skilled enough to work out every possibility of writing these words.
I have no way of changing the textarea
to other, better plugins or editors as it's already part of a functioning script.
Any helpful idea would be greatly appreciated.
EDIT: One additional question
I got really helpful answers to my question, Thank you everyone. I do have an additional question though. What if, other then checking that it's not part of a word, I also want to check that it's not preceded or followed by a .
period. I tried adding (?!\.)
at the beginning of it, but that doesN't work at all. Is there a way to check for that as well?
//EDIT: Never mind, I figured it out. it's \b(?!\.)something(?!\.)\b for the check at the start and end of the word.
Something like this? ( °_• )
var txt="or some text or before (.)or(.) anywhere Or";
console.log(txt.replace(/\bor\b/gi,"OR"));
// "OR some text OR before (.)OR(.) anywhere OR"
Matching on a word boundary \b
may suit:
'foo or bar'.replace(/\bor\b/, 'OR'); // foo OR bar
You can also provide a function to replace, so:
'foo or bar'.replace(/\b(or)\b/, function(m){return m.toUpperCase()})); // foo OR bar
which might be good for cases where you have multiple possible matches:
'foo or bar and fum'.replace(/\b(or|and)\b/ig, function(m){return m.toUpperCase()}); // foo OR bar AND fum
Something like this:
'(something)or(somethingelse) before or oR Or OR oreos thor'.replace([^\w]([oO][rR])[^\w], 'OR');