Removing special characters from a string

Currently working on making a palindrome function. I have the gist of it. Just can’t get this last part.
I’ve tried so many examples from so many stockoverflow posts and this still doesn’t work for me.
Can someone help me figure out what’s wrong?

var str = "abc's test#s";


Did you first try solving it on your own?

Yes. I have a majority of it worked out already:
I just can’t remove the special characters.

what is the purpose of the replace above? how is it related to palindromes?

For the test cases, they’ve included strings with special characters.
so “rac!!*&ecar&” and “e_ye” should still be considered a palindromes in that case.

I’m supposed to be using the .replace() method to remove them. It seems others can do it. But I’m still not sure how I’m messing it up.

Keep in mind that some functions change the string or function upon which they’re working, and some don’t but return the changed value that you can assign to something. If you don’t know, it’s good to check.

1 Like

great - so the purpose of replace is to remove certain characters - then why do you have _ as the replacement character?

It’s an algorithm challenge.

You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.

Note the wording of that: all non-alphanumeric characters. That means you have only two ranges of characters not to remove: a-z and 1-9 (A-Z isn’t required, given that you’ve already lowercased the string).

With regexes, you can use ^ for negation.

1 Like

I know the problems - I’m asking OP to state his/her intent

My intent was to only out the last step: replace.
I wasn’t asking for help with the whole algorithm. I’m just focusing on the one part of it I’ve been having trouble with for some time now. The code I posted above is one of the many examples I’ve been referencing .

I’ve tried it here in a separate document and I’m still unable to remove the “#” or “’” characters. That’s why I’m wondering if there’s something else I’m missing.

I just don’t understand why this one part isn’t working.

Once I figure this out, I can understand the rest.

1 Like

I see - you’re just trying out replace with _ to see it working - in that case it’s what @ksjazzguitar points out - replace does not modify the string itself - it returns a new string

1 Like

Thank you for paraphrasing that. That’s what I needed to know.

the important concept here is strings in javascript are immutable - meaning the characters in a string cannot be changed - this is quite confusing at first because strings can behave like arrays and have similar methods - but array elements can be modified - you have to carefully read the return value description in the MDN documentation for every function

1 Like

Try this:

const newStr = str.replace(/[_\W]/g, “”);