Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(get-string-match): trim strings #2927

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/neat-kings-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@contentful/f36-utils": patch
---

fix(get-string-match): trim strings
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getStringMatch } from './getStringMatch';

describe('getStringMatch', () => {
it('should return before, match, and after', () => {
it('returns before, match, and after', () => {
const base = 'some test string';
const match = 'test';
expect(getStringMatch(base, match)).toEqual({
Expand All @@ -10,7 +10,7 @@ describe('getStringMatch', () => {
after: ' string',
});
});
it('should work with special characters', () => {
it('works with special characters', () => {
const base = 'string with regex characters (test)';
const match = '(test';
expect(getStringMatch(base, match)).toEqual({
Expand All @@ -19,12 +19,30 @@ describe('getStringMatch', () => {
after: ')',
});
});
it('should work with any regex special character', () => {
it('works with any regex special character', () => {
const base = '.*+?^${}()|[]\\';
const characters = base.split('');
characters.forEach((character) => {
const { match } = getStringMatch(base, character);
expect(match).toEqual(character);
});
});
it('works with whitespace', () => {
const base = 'Component - Author';
const match = 'author ';
expect(getStringMatch(base, match)).toEqual({
before: 'Component - ',
match: 'Author',
after: '',
});
});
it('ignores capitalisation', () => {
const base = 'Author';
const match = 'author';
expect(getStringMatch(base, match)).toEqual({
before: '',
match: base,
after: '',
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface MatchObj {
*/
export function getStringMatch(base: string, match: string): MatchObj {
const matchResult = { before: '', match: '', after: '' };
const escapedMatch = match.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedMatch = match.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

const regex = new RegExp(
`(?<before>.*?)(?<match>${escapedMatch})(?<after>.*)`,
Expand Down
Loading