-4

How to change word to be uppercase in string?

for example I have this string: \u001b[31merror\u001b[39m and if the error word is exist then I want to make her uppercase, so the output should be: \u001b[31mERROR\u001b[39m.

Why when I use regex it will not work? \u001b[31merror\u001b[39m.replace( /(error)/, "$1".toUpperCase())

error can be any lowercase word

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jon Sud
  • 10,211
  • 17
  • 76
  • 174

2 Answers2

1

It doesn't work because the toUpperCase() is applied at the string "$1" and then the result of that operation i passed as second argument of the replace method; you instead expect that toUpperCase is called with the value found. To do so, you need to pass a function as second argument of replace:

"\u001b[31merror\u001b[39m".replace(/(error)/, $1 => $1.toUpperCase())

That would work (notice, $1 here is just an arbitrary variable name, you can call it as you want).

However, since you said that error is just an example, you could either list all the possible values:

mystring.replace(/(error|info|warning)/, $1 => $1.toUpperCase())

Or just replace everything is between \u001b[31m and \u001b[39m (assuming they don't change):

const mystring = `\u001b[31merror\u001b[39m`;
console.log(
  mystring.replace(/\u001b\[31m(.*)\u001b\[39m/, $1 => $1.toUpperCase())
);

Hope it helps.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
ZER0
  • 24,846
  • 5
  • 51
  • 54
-1

Use this

'\u001b[31merror\u001b[39m'.replace(/(error)/, RegExp.$1.toUpperCase())

This will replace the string 'error' and change it to 'ERROR'

Faisal Rashid
  • 368
  • 1
  • 11