Check for Palindromes: Would a ``` for loop ``` help? Removing non-Alphanumeric Characters in Javascript?

Not sure how to get started on this one. I’ve heard a for loop is a good idea.

1 Like

Yes, I used a for loop in my solution. You’ll want to standardize your string inputs first (change all characters to lowercase, remove anything that’s not alphanumeric). Next, find a way to iterate through the characters and check if the strings match both backward and forward. Anytime you need to iterate through something, a for loop works well :slight_smile:

3 Likes

If you need to do something with each element of a list, then yes.

There are also easier(high level) ways in JavaScript.For example, you don’t need a loop to replace characters in strings, you just need https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace it will do the job for you.

If you don’t know how to get started, consider this situation.You don’t have a computer, just a pen and a sheet of paper, and you’re given two 1000-characters words.How would you proceed to check palindromes ?

1 Like

Omegga that is a great question.

So I understand a for loop has three components. How would I use them to find non-alphanumeric characters?

So this is how I am starting.

function palindrome(str) {
  str.replace().toLowerCase();
  var newString;
  // Good luck!
  return true;
}



palindrome("eye");

I don’t think you need the replace for changing to lower case, just .toLowerCase works fine.

I found this stackoverflow answer very helpful for removing non-alphanumeric characters, for which I used the replace method.http://stackoverflow.com/questions/9364400/remove-not-alphanumeric-characters-from-string-having-trouble-with-the-char

1 Like

function palindrome(str) {
  str.replace(/\W/g, ' ');
  str.toLowerCase();
  var newString;
  // Good luck!
  return true;
}



palindrome("eye");

This is what I got out of the stackoverflow thing you sent me. Good start? I’m not sure if that function removes the underscores though. I guess I’m just confused as to how much str.replace(/\W/g, ' '); actually removes.

Yup, that’s a good start. So str.replace(/\W/g, ’ '); let’s look at this line. replace takes two arguments, first what we are “looking” to replace, and what we will replace it with. Your first argument is fine, /\W/g is a regex, and to just break this down real quick… the /\W/ means match anything that is not a letter or a number, and that includes white space. The g is a global flag that basically means don’t stop after it finds one match, keep going until it’s gone through the whole string. The second part of your replace poses a bit of a problem… you’re saying take anything that isn’t a letter or a number and replace it with a whitespace. I think what you want is to get rid of those special characters and not put anything in there… so that “e%ye” would become “eye” and not “e ye”. So change the second argument to just be ‘’. Two single quotes with no space in between.
Now, with str.toLowerCase(); You have the right idea, you want to change everything to lowercase to simplify the comparison, but the problem is the function toLowerCase() doesn’t actually change the existing string, it creates a new string with everything in lowercase. So after that call, str would actually remain the same. So either you want to create a new String to hold the modified String, or just set it equal to itself like str = str.toLowerCase();
So you’re halfway there I think! I hope this helps and doesn’t confuse you more. :slight_smile:

6 Likes

I just feel like I need to go through how to use basic javascript again. One and done on each exercise doesn’t do it for me. Feeling pretty overwhelmed with my current understanding of coding.

2 Likes

I can totally relate to that. That’s how I felt when I first encountered those front end exercises (make a tribute page, portfolio, etc). “Here let’s edit this make believe cat app by adding a picture and manipulating wells with jQuery… ok now go make stand alone webpages.” Boom, right into the deep end of the pool. I went to Udemy and bought a couple of courses on html/css/bootstrap to help me understand what the heck was going on.

I would suggest looking at some Udemy courses, they are all 10 dollars right now. I can suggest a couple that I think would be good javascript beginning courses that’ll get you up to speed a better than these one and done examples. Another great resource is CodeAcademy, they have a free Javascript course you could take. Bookswise if you’re just stumped on how to think like a programmer, there’s a great book I’m reading through called, ironically enough, “Think Like a Programmer.” You can find it on Amazon and check out the reviews. It’s based on C++, but you can follow along and do the examples in Javascript.

Just keep hammering away, even if it feels like you’re not moving forward…persistence really is the key.

3 Likes

Really though, I just want to know what goes after var newString

For removing non-alphanumeric characters, what you have there does leave the underscores. Just under that on the stackoverflow page they offer an alternative RegEx that will leave just alphanumeric characters in your string: input.replace(/[^0-9a-z]/g, ''). The caret means that instead of replacing these characters, 0-9 and a-z will be the only characters left behind.

Like clockwerkz said, you should assign your replace function to the newString variable because replace() won’t actually alter str.

In my own solution (which works, but may not be the best way) I separated my string characters into an array and used that to check for equivalency. So that was the next step after cleaning up the strings.

3 Likes

That’s the regex I used… /[^0-9a-z]0/. I looked up \W and it seems to do the same thing, but when I plugged it in to my solution it didn’t get rid of the underscore. So yeah, maybe just use that replace command instead of the \W.

But before all this, I think you could use a step back and look at something like CodeAcademy to help strengthen the basics down.

Omegga’s suggestion of looking at the problem from a pen and paper point of view is great, too.

1 Like

Clockwerkz,

I’m jumping into Jonas Schmedtmann’s JS course on udemy and it is working so well. I understand the code infinitely better now! I would recommend it to anyone just learning code or needing a refresher.

Here’s a working solution that uses regexp. Only took me 5 hours of regexp research and no experience with replace() methods, but it works! In order to solve this problem, you have to first clean the argument of the non alphanumeric characters and assign it to a new variable. Then you have to create a new variable that ‘palindromes’ if you will. Then you have to test the cleanPalindrome with the ‘palindromed’ Palindrome, if that makes sense. If it matches, return true, if not return false.

function palindrome(str) {

// Clean the palindrome from all the non alphanumeric characters
var cleanPalindrome = str.replace(/[^0-9a-z]/gi, ‘’).toLowerCase();

// Now I have to ‘palindrome’ the palindromeClean and see if it matches the
var palindromeReverse = cleanPalindrome.split(’’).reverse().join(’’);
var newPalindrome = palindromeReverse.toLowerCase();

// Testing the palindrome case
if (newPalindrome === cleanPalindrome ) {
return true;
}
return false;
}

palindrome(“five|_/|four”);

it works … awesome. Actually you don’t need the ‘toLowerCase()’ method twice, though. After you reverse the word, just compare the two variables ‘cleanPalindrome’ and palindromeReverse with each other and it still works.

RegExp is cool but without it you can do it like this

  str = str.toLowerCase().split("").
  filter(function(x){ return x !== x.toUpperCase() || Number.isInteger(x) });

  //x !== x.toUpperCase() checks whether or not x is a letter

   return str.join("") === str.reverse().join("");

   //for some reason it never works when comparing arrays so you have to join

// This method will work
function palindrome(str) {
var re = /[\W_]/g;
var result = str.toLowerCase().replace(re, ‘’);

if(result.length >=1 || result.length === 0) {
for(var i = 0; i< result.length; i++) {
if(result[i] !== result[result.length-1-i]) {
return false;
}
}

}
return true;

}

You really only need to search the half length of the string (+1 if it is an odd number) and then you can return.

Thank you soo much for that reply! Didn’t had any problems with reversing and comparing strings but getting proper regex was huge problem for me. Thanks to your reply I finally understood what that regex do! :slight_smile: