0

I am trying to solve a palindrome problem. The palindrome can contain letters and numbers, but everything else must be removed. My code below is not returning the correct result.

function palindrome(str) { const regex = /[\s]|[[:punct:]]/gi; // const regex = /age/gi; const string = str.replace(regex, "").toLowerCase().split(""); console.log(string); let aPointer = 0; let bPointer = string.length - 1; while (aPointer <= bPointer) { if (string[aPointer] !== string[bPointer]) { return false; } aPointer += 1; bPointer -= 1; } return true; } console.log(palindrome("My age is 0, 0 si ega ym.")); 

The output removes the spaces but not the punctuation. Am I getting the syntax wrong?

2

3 Answers 3

2

You could use the following:

const regex = /[^a-zA-Z0-9]/gi; 

This matches everything that is not a letter or number. You can just add any other exclusions that you may need.

Sign up to request clarification or add additional context in comments.

Comments

0

Try the below regex:

const regex = str.replace(/(~|`|!|@|#|$|%|^|&|\*|\(|\)|{|}|\[|\]|;|:|\"|'|<|,|\.|>|\?|\/|\\|\||-|_|\+|=)/g,""); 

1 Comment

What about characters that are not on the list? @ScottWells said they wanted only letters and numbers. If some character happens to not be on the list it could still slip through.
0

Your regex expression looks unusual. I've never heard of :punct: for matching punctuation.

When I run that regex, it matches (space), :], [], p], u], n], c], and t]. A screenshot of the syntax highlighting for the expression you used (from RegExr):

highlighted regex So that regex will match either whitespace OR any character in [:punct and then a ].

Changing your regex to: /[^A-Za-z0-9]/gi should solve your problem.

This regex will match anything that is NOT in the ranges A-Z, a-z, or 0-9 so you can remove it.

Edit: Apparently PCRE (PHP) regex allows using [:punct:] for matching punctuation. Regex in JavaScript does not use this and matches it literally.

3 Comments

Also, I highly recommend RegExr for checking your regex expressions. It has syntax highlighting, will automatically test your expression against text you put in, and gives you an explanation of what your regex does. Regexr
I have been using regex101.com. That's how I built my regex initially. I'll have to give this a shot.
Oh... I think I may have figured out why you were using [:punct:]. regex101.com uses PCRE (PHP) by default, which uses [:punct:]. If you choose the javascript flavor it then works as it does in javascript code, and matches [:punct:] literally.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.