Home > Software engineering >  str.replace() bug? javascript
str.replace() bug? javascript

Time:11-17

const str = 'test'
const newStr = str.replace(str[3],str[3].toUpperCase())
console.log(newStr) // output: 'Test'

const str2 = 'hello'
const newStr2 = str2.replace(str2[3],str2[3].toUpperCase())
console.log(newStr2) // output: 'heLlo'

what does go wrong?

expecting result: 'tesT'

expecting result: 'helLo'

CodePudding user response:

.replace( x, y) Would replace the first occurance of x with y

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

  • Related