Skip to content

Commit

Permalink
Implement skipWord option
Browse files Browse the repository at this point in the history
Fixes #16
  • Loading branch information
grncdr committed Oct 24, 2021
1 parent 887b0b0 commit 49a998e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,26 @@ test('Capitalize words, handling shorthand ordinals (1st, 2nd, 3rd) correctly',
})
```

and thanks to a suggestion from [@Songyu-Wang](https://github.com/grncdr/js-capitalize/issues/16), capitalize supports skipping words that should never be capitalized (e.g. articles and coordinating conjunctions in English).

```javascript
test('Title-case words, by providing a skipWord regex', function (t) {
t.plan(1)
var opts = { skipWord: /^(a|the|an|and|or|but|in|on|of|it)$/ }
t.equal(
capitalize.words('the story of an unlikely feature and the way it was implemented', opts),
'The Story of an Unlikely Feature and the Way it Was Implemented'
)
})

test('Title-case words, by providing a skipWord callback', function (t) {
t.plan(1)
t.equal(
capitalize.words('this is nice eh?', { skipWord: (word) => word.length < 3 }),
'This is Nice eh?'
)
})
```

## Install

Expand Down
15 changes: 14 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ capitalize.words = function (string, opts) {
var nonWord = /[^0-9a-zA-Z\u00C0-\u017F\u0400-\u04FF]+|$/g
var match
var out = ""
var count = 0

while (match = nonWord.exec(string)) {
var sep = match[0]
Expand All @@ -34,8 +35,14 @@ capitalize.words = function (string, opts) {
out += word[0]
word = word.substring(1)
}
out += capitalize(word, opts) + sep
if (typeof opts.skipWord === 'function' && opts.skipWord(word, count)) {
out += word
} else {
out += capitalize(word, opts)
}
out += sep
startOfWord = nonWord.lastIndex
count++
if (startOfWord == string.length) {
break
}
Expand All @@ -51,6 +58,12 @@ function normalizeOptions(opts) {
if (typeof opts === 'boolean') {
return { preserve: opts }
}
if (opts.skipWord instanceof RegExp) {
const rgx = opts.skipWord
opts.skipWord = function (word, position) {
return position > 0 && rgx.test(word)
}
}
return opts || {}
}

Expand Down

0 comments on commit 49a998e

Please sign in to comment.