Skip to content

Commit

Permalink
Handle leading and embedded quotes
Browse files Browse the repository at this point in the history
Fixes #15
  • Loading branch information
grncdr committed Oct 24, 2021
1 parent cee5a68 commit 887b0b0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
12 changes: 11 additions & 1 deletion README.md
Expand Up @@ -78,13 +78,23 @@ test('Capitalize words with cyrillic characters', function (t) {
})
```

and thanks to [@ultraflynn](https://github.com/grncdr/js-capitalize/pull/3), capitalize properly handles quotes within the string:
and thanks to [@ultraflynn](https://github.com/grncdr/js-capitalize/pull/3) and [@DatGuyJonathon](https://github.com/grncdr/js-capitalize/issues/15) capitalize properly handles quotes within the string:

```javascript
test('Capitalize each word, ignoring quotes', function(t) {
t.plan(1)
t.equal(capitalize.words("it's a nice day"), "It's A Nice Day")
})

test('Quotes test case 2', function(t) {
t.plan(1)
t.equal(capitalize.words("It’s a Boy"), "It’s A Boy")
})

test('Handles embedded quotes', function(t) {
t.plan(1)
t.equal(capitalize.words("'There's angels among us'"), "'There's Angels Among Us'")
})
```

and thanks to [@sergejkaravajnij](https://github.com/grncdr/js-capitalize/pull/9), capitalize also supports a second boolean parameter to preserve casing of the rest of the strings content:
Expand Down
30 changes: 23 additions & 7 deletions index.js
Expand Up @@ -7,22 +7,38 @@ function capitalize (string, opts) {
return string.charAt(0).toUpperCase() + string.substring(1);
}

// a QUOTE character immediately followed by a word character
var QUOTE = /['"`’]/
var WORD = /[0-9a-zA-Z\u00C0-\u017F\u0400-\u04FF]/

capitalize.words = function (string, opts) {
opts = normalizeOptions(opts)
if (!opts.preserve) {
string = string.toLowerCase();
}
var start = 0
var nonWord = /[^0-9a-zA-Z\u00C0-\u017F\u0400-\u04FF']+|$/g
var startOfWord = 0
var nonWord = /[^0-9a-zA-Z\u00C0-\u017F\u0400-\u04FF]+|$/g
var match
var out = ""

while (match = nonWord.exec(string)) {
var suffix = match[0]
var word = string.substring(start, nonWord.lastIndex - suffix.length)
out += capitalize(word, opts) + suffix
start = nonWord.lastIndex
if (start == string.length) break
var sep = match[0]
var sepStart = nonWord.lastIndex - sep.length
if (QUOTE.test(string[sepStart]) && WORD.test(string[sepStart + 1])) {
// don't capitalize after an embedded quote
continue
}
var word = string.substring(startOfWord, nonWord.lastIndex - sep.length)
if (QUOTE.test(word[0])) {
// strip leading quote
out += word[0]
word = word.substring(1)
}
out += capitalize(word, opts) + sep
startOfWord = nonWord.lastIndex
if (startOfWord == string.length) {
break
}
}

return out
Expand Down

0 comments on commit 887b0b0

Please sign in to comment.