Skip to content

Commit

Permalink
fix(utils): enhance capitalizeBetweenPunct function
Browse files Browse the repository at this point in the history
- Improve regex to handle multiple punctuated sections
- Remove reliance on spaces for identifying sections
- Ensure remaining text is capitalized after processing punctuated sections
- Fix issue where unmatched sections were not correctly capitalized
  • Loading branch information
Mara-Li committed Dec 15, 2024
1 parent 1a592b7 commit 59e3c5e
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions packages/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,21 @@ export const isNumber = (value: unknown): boolean =>
value.trim().length > 0));

export function capitalizeBetweenPunct(input: string) {
const regex = /(?<open>\p{P})(?<enclosed>.*?)(?<close>\p{P})(?<spaces>\s+)(?<rest>.*)/u;

const match = input.match(regex);
if (!match || !match.groups) return input.capitalize();

const { open, enclosed, close, spaces, rest } = match.groups;
return `${open}${enclosed.capitalize()}${close}${spaces}${rest.trim().toTitle()}`.capitalize();
// Regex to find sections enclosed by punctuation marks
const regex = /(?<open>\p{P})(?<enclosed>.*?)(?<close>\p{P})/gu;
let remainingText = input;
let result = input;
for (const match of input.matchAll(regex)) {
const { open, enclosed, close } = match.groups ?? {};
if (open && enclosed && close) {
const capitalized = enclosed.capitalize();
result = result.replace(match[0], `${open}${capitalized}${close}`);
remainingText = remainingText.replace(match[0], "").trim(); // Remove processed section
}
}
remainingText = remainingText.toTitle();
result = result.replace(new RegExp(`\\b${remainingText}\\b`, "gi"), remainingText);
return result;
}

export * from "./src/errors";

0 comments on commit 59e3c5e

Please sign in to comment.