I’d like to replace only the alphanumeric characters in the original string with
.replace(“”, /[^a-z 0-9]+$/g). I’m not quite sure how to go about this.
Does .replace(/[^A-Z0-9]/ig, “_”) not delete uppercase letters? How did you then change them to lowercase letters with .replace(/_/ig, “”).toLowerCase()?
.replace(/[^A-Z0-9]/ig, “_”) - Will replace all special characters except to “_” .replace(/_/ig, “”).toLowerCase() - This 2 operations replace all _ to “” and convert all to lowercase.
I did not write a single expression to both at once. We can optimize the RegEx
I’m still confused. To me, .replace(/[^A-Z0-9]/ig, “_”) gives the command to replace /[^A-Z0-9]/ig with “_”, not to ignore “_”. .replace(/_/ig, “”) looks to be formatted the same as .replace(/[^A-Z0-9]/ig, “_”) yet gives a different command. What am I missing?
For Check for Palindromes, the advanced solution includes .match() methods to replace any non-alphanumeric characters. Why use .match() when it is supposed to return an array with the the corresponding string characters? Like most people, I had only thought of .replace().
My approach takes longer I believe, but is a bit different:
function palindrome(str) {
// split the input into an array
var array = [];
var string = str.toLowerCase();
// filter array of white space and non alphanumeric values
string = string.replace(/[^0-9a-z]/gi, '');
array = string.split("");
// Create first and last letter to compare
var firstChar;
var lastChar;
var length = Math.floor((array.length)/2);
// Compare using a for loop at lenght/2
for(var i = 0; i < length; i++){
firstChar = array.shift();
lastChar = array.pop();
if (firstChar !== lastChar){
return false;
}
}
// If statement, if a != b then false
return true;
}
function palindrome(str) {
// Good luck!
var firstStr = str.toLowerCase();
var secStr = firstStr.replace(/\s/g, “”);
var thirdStr = secStr.replace(/[. ,:-_-/()]+/g, “”);
var arr = [];
arr= thirdStr.split(’’);