Drill

ProblemsJavaScript › patterns

Mirror text, ignoring the clutter

easypatternsTwo pointersStringsJavaScript

An audit tool checks whether a phrase reads the same forwards and backwards once the formatting — spaces, punctuation, digits — is stripped away.

isCleanPalindrome(text: string) → bool

Solve it in the editor →

Where you start

function isCleanPalindrome(text) {
  
}

Worked examples

CallResult
isCleanPalindrome("race a car")false
isCleanPalindrome("A man, a plan, a canal: Panama")true
isCleanPalindrome("racecar")true
isCleanPalindrome(" ")true

Hint

Walk from both ends at once, skipping anything that is not a letter or digit, and compare the survivors.

Reference solution in JavaScript
function isCleanPalindrome(text) {
  let i = 0, j = text.length - 1;
  while (i < j) {
    const a = text[i], b = text[j];
    if (!/[a-zA-Z0-9]/.test(a)) { i++; continue; }
    if (!/[a-zA-Z0-9]/.test(b)) { j--; continue; }
    if (a.toLowerCase() !== b.toLowerCase()) return false;
    i++; j--;
  }
  return true;
}

The same problem in another language

More patterns problems in JavaScript