0

Why the following code returns "ZZZCamelCase"?? Doesn't such regex examine if the string starts and ends with small case a-z? As what I understand, the str variable should match such condition, so the console output should be "ZZZZZZZZZZZZ", but obviously it somehow breaks the str, and examine the substring against the regex. Why? and how can I tell the program to treat "testCamelCase" as one string?

var str = "testCamelCase"; 
console.log(str.replace(/^[a-z]+/, 'Z')); // ZZZCamelCase
Blake
  • 7,367
  • 19
  • 54
  • 80
  • 1
    @fuyushimoya Also to mention, no `i` flag – Tushar Oct 15 '15 at 11:15
  • "Doesn't such regex examine if the string starts and ends with small case a-z?" No. – dievardump Oct 15 '15 at 11:21
  • It is not clear to me what duplicate it is. The number of `Z` in the expected result was different in the beginning. Now, the regex just needs to match any Latin letter. If it is, this post must be closed. – Wiktor Stribiżew Oct 15 '15 at 11:24
  • You just need to read about quantifiers and global matching with [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). It is basic regex knowledge. – Wiktor Stribiżew Oct 15 '15 at 11:31
  • my actual doubt is: if `^[a-z]+` means to match anything starts and ends with a-z, then why "testCamelCase" didn't pass the test? It seems this regex doesn't only check the beginning and end letter, but also the letters in between. – Blake Oct 15 '15 at 11:31

2 Answers2

2

Here you are matching one or more lower case letters. That's going to be 'test' in your string, because after that comes an uppercase 'C'. So only 'test' gets rpelaced by 'ZZZ'

console.log(str.replace(/^[a-z]+/, 'ZZZ')); // ZZZCamelCase

Use

str.replace(/[a-z]/ig, 'Z')

to get 'ZZZZZZZZZZZZ'

Simon H
  • 20,332
  • 14
  • 71
  • 128
2

You are forgetting, that regex is case sensitive. This means, that [a-z] doesn't capture the whole string. [a-zA-Z] does. So does [\w] including digits from 0-9.

Marco
  • 22,856
  • 9
  • 75
  • 124