Skip to content

Commit

Permalink
fix(toCapitalized): remove lookbehind regular expression in order to …
Browse files Browse the repository at this point in the history
…support iOS Safari <v16 (#3721)

The test does fail when using the regexp version:

<img width="490" alt="Screenshot 2024-06-18 at 22 08 08"
src="https://github.com/dnbexperience/eufemia/assets/1501870/41be2650-a779-46c4-9934-75eb36c4005d">

Reprod:
https://codesandbox.io/p/sandbox/eufemia-js-ios16-issue-gz77wm?file=%2Fsrc%2FApp.js%3A7%2C5
  • Loading branch information
tujoworker authored Jun 18, 2024
1 parent 8b37058 commit eb53409
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
20 changes: 20 additions & 0 deletions packages/dnb-eufemia/src/shared/__tests__/component-helper.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -524,15 +524,35 @@ describe('"toKebabCase" should', () => {
})

describe('"toCapitalized" should', () => {
let replaceSpy
beforeEach(() => {
replaceSpy = jest.spyOn(String.prototype, 'replace')
})
afterEach(() => {
replaceSpy.mockRestore()
})

it('capitalize the first letter of every word', () => {
expect(toCapitalized('first word æøå')).toBe('First Word Æøå')
})
it('capitalize the first letter of every word even if there is a space', () => {
expect(toCapitalized(' first word æøå')).toBe(' First Word Æøå')
})
it('capitalize the first letter after a dash', () => {
expect(toCapitalized('first-word')).toBe('First-Word')
})
it('capitalize supports non string values', () => {
expect(toCapitalized(undefined)).toBeUndefined()
})
it('should not use replace with lookbehind regexp to support older browsers', () => {
replaceSpy.mockImplementationOnce(() => 'First Word')
expect(String.prototype.replace).toHaveBeenCalledTimes(0)
expect(toCapitalized('first word')).toBe('First Word')
expect(
String(String.prototype.replace.mock.calls?.[0]?.[0])
).not.toContain('?<=')
expect(String.prototype.replace).toHaveBeenCalledTimes(0)
})
})

describe('"makeUniqueId" should', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/dnb-eufemia/src/shared/component-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,13 @@ export function toCapitalized(str) {
return typeof str === 'string'
? str
.toLowerCase()
.replace(/(?<=(^|\s|-))(.)/g, (l) => l.toUpperCase())
.split('')
.map((char, index, arr) =>
index === 0 || arr[index - 1] === ' ' || arr[index - 1] === '-'
? char.toUpperCase()
: char
)
.join('')
: str
}

Expand Down

0 comments on commit eb53409

Please sign in to comment.