What is the correct regex for superTrim() to satisfy the description and pass the test:
// removes all leading and trailing whitespace, newlines, escaped whitespace,
// escaped punctuation, punctuation, special characters, etc
// - EVERYTHING leading and trailing that is not alphanumeric.
const superTrim = (src: string) => src.replace(/<-- correct regex here --> /gm, "").trim();
if (import.meta.vitest) {
const { describe, expect, it, test } = await import("vitest");
test("superTrim", () => {
expect(superTrim("John Smith")).toBe("John Smith");
expect(superTrim("Bobby Lee\n \n, ")).toBe("Bobby Lee");
expect(superTrim("Sally Maen n, ")).toBe("Sally Mae");
expect(superTrim("JCP Dept. Stores\nAttn: Marketingn , 'n '"))
.toBe("JCP Dept. Stores\nAttn: Marketing");
});
}
I did find some similar but different enough existing questions that I think a new question is warranted. I could iterate over the string identifying markers to return a slice but this seems to be regex solution.
2
Answers
You can use this regularity to fulfill your requirements:
(^[W\n]*)|([W\n]*$)
You just need to capture and return the part you want:
Regex capturing groups:
^(\+[0-9a-zA-Z]|[^0-9a-zA-Z])*
At the beginning of the string matches EITHER a literal
one or more times followed by a single alphanumeric, OR any single non-alphanumeric, zero or more times as many times as possible (greedy).
(.*?)
the piece you seekAnything and everything, left in the middle (non-greedy).
([^0-9a-zA-Z]|\+[0-9a-zA-Z])*$
Same as 1, but anchored at the end of the string with the
|
(OR) reversed just for symmetry