JavaScript Check for palindrome (spaces & punctuation included) - javascript

Trying to check for palindromes. I've checked other answers but none included punctuation & spaces.
"never odd or even" and "A man, a plan, a canal. Panama" Should return true but they don't.
function palindrome(str) {
if(str.replace(/[^\w\s]|_/g, "").toLowerCase() === str.replace(/[^\w\s]|_/g, "").toLowerCase().split("").reverse().join("")){
return true;
} else {
return false;
}
}
palindrome("eye");

I think you have an error in your RegEx. If you want to remove the spaces, you don't need that \s. Try changing:
str.replace(/[^\w\s]|_/g, "")
With
str.replace(/[^\w]|_/g, "")

Use instead:
str.replace(/\W/g, "")
Which will replace any non-word char by empty string.

You can try with a simpler regex which simply replaces any character that is not in the alphabet?
function palindrome(str) {
if(str.replace(/[^a-zA-Z]/g, "").toLowerCase() === str.replace(/[^a-zA-Z]/g, "").toLowerCase().split("").reverse().join("")){
return true;
} else {
return false;
}
}

This is similar to the above but reformatted:
function palindrome(str) {
let regex = /[^a-zA-Z]/g;
return str.replace(regex, '').toLowerCase() === str.replace(regex, '').toLowerCase().split('').reverse().join('');
}

Related

palindrome regex

function palindrome(str) {
// Good luck!
var a = str.replace(/\s|[0-9_]|\W|[#$%^&*()]/g, "").toLowerCase();
if (a === a.split("").reverse().join("")) {
return true;
}
return false;
}
palindrome("eye");
palindrome("1 eye for of 1 eye.") //should return false.
I have done this task on freecodecampus.com. Can anyone tell me why it should give false? If we are removing dot and punctuations, then isn't it right that it should return true?
According to your comment "Note You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols)", you have to keep alphanumeric characters (ie. letters AND digits). So remove NON alphanum characters (ie. [\W_]). \W is the negation of \w: [^a-zA-Z0-9_]
This is done with:
var test = [
"racecar",
"RaceCar",
"race CAR",
"2A3*3a2",
"2A3 3a2",
"2_A3*3#A2",
"1 eye for of 1 eye."
];
function palindrome(str) {
var a = str.replace(/[\W_]+/g, "").toLowerCase();
if (a === a.split("").reverse().join("")) {
return true;
}
return false;
}
console.log(test.map(function (a) {
return a+' : '+palindrome(a);
}));
function palindrome(str) {
// Good luck!
var a = str.replace(/\s|[0-9_]|\W|[#$%^&*()]/g, "").toLowerCase();
// Here print a
// a = "eyeforofeye"; which is perfect palindrome
if (a === a.split("").reverse().join("")) {
// will pass this condition
return true;
}
return false;
}
palindrome("1 eye for of 1 eye.")
See my comments in the code. The replace method is using a regex to replace all numbers, special character and spaces with nothing. So all you get is a single word with no spaces, numbers and special characters.
In your case you will get eyeforofeye which is perfect palindrome.
You are doing a Rube Goldberg process by providing an overly complicated Regular Expression which could be shorten to /[^a-z]/ and it doesn't return false if you execute your code.
function palindrome(str) {
var a = str.replace(/[^a-z]/ig, '').toLowerCase();
return a === a.split('').reverse().join('');
}
console.log(palindrome('race CAR'));
console.log(palindrome('2A3 3a2'));
console.log(palindrome('eye'));
console.log(palindrome('1 eye for of 1 eye.'));
console.log(palindrome('stack'));
Thanks a lot folks, have done it; Also got some good information on RegeXes. Reading RegEx from Eloquent Javascript, can anyone suggest another better source? Thanx ahead
By the Way As an Answer it took this, ( for those who are interested in answer that passes all ticks in project) ,
function palindrome(str) {
// Good luck!
var a = str.replace(/[^a-z0-9]/ig, "").toLowerCase();
if (a === a.split("").reverse().join("")) {
return true;
}
return false;
}
palindrome("eye");

Javascript regex for palindrome?

<code>
function palindrome(str) {
// Good luck!
str=str.toLowerCase();
str=str.replace(/[^\Wa-z0-9]/gi," ");
str=str.replace(/[.,\s]/g, '');
str=str.replace(/\//g, "");
str=str.replace("(", "").replace(")", "").replace("0-0", "").replace(":-", "").replace(":","");
var a=str.split("");
a=a.reverse();
a=a.join("");
if(str===a){
return true;
}
else {
return false;
}
}
palindrome("0_0 (: /-\ :) 0-0");
</code>
Note : I am trying here to remove all the special characters,spaces, and uppercase character and checking that if the passed argument is palindrome or not. I just want to know if there is a way to make the regex concise to only one line.
str = str.toLowerCase().replace( /[^a-z0-9]/g, '' );
Will lowercase the string and remove all non alphanumeric characters.

How to check if a string is a palindrome JavaScript [CLOSED!]

I'm trying to make a function that will check if a word is a palindrome. If the word is a palindrome it will return true else it will return false. "You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.
We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others."
My code is:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]+/g,"");
if (str === str.split("").reverse().join("")){
return str;
} else {
return "This is not a palindrome";
}
}
Could somebody tell me what is wrong with this code please?
How about this solution.
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z0-9]+/g,"");
return str === str.split("").reverse().join("");
}
It strips non alpha-numeric characters, turns into lower case, and returns true | false
"alphanumeric" means both alphabetical and numerical characters. Try something like this:
function isPalindrome(str) {
str = str.toLowerCase().replace(/[^a-z0-9]+/g, '');
return str === str.split('').reverse().join('');
}
isPalindrome('racecar')
// => true
isPalindrome('race car')
// => true
isPalindrome('race caR')
// => true
It doesn't work because it always return a "true" because if not palindrome, then return a string, which evaluated as a boolean is true.

Palindrome Checker in JavaScript - don't know how to debug

I want to build a palindrome checker in javascript. All non-letter characters should be removed, so that a phrase like "A man, a plan, a canal. Panama" can also be a palindrome.
function reverse(str) {
return str.split("").reverse().join("");
}
function palindrome(str) {
str = str.replace(/[^a-zA-Z]+/,"").toLowerCase();
if(str == reverse(str)) {
return true;
}
else {
return false;
}
}
Now, where is the mistake in the above lines?
The code works on some examples. But for instance "A man, a plan, a canal. Panama" and "never odd or even" return false, meaning somewhere has to be a mistake.
You need to provide the global match flag to your regex:
/[^a-zA-Z]+/g
^
This is a common misconception. The replace() method does not replace all instances of what you want to replace in a string. It simply replaces the first instance and stops. If you refactor your regEx like this:
function reverse(str) {
return str.split("").reverse().join("");
}
function palindrome(str) {
var find = "[^a-zA-Z]";
var regEx = new RegExp(find, 'g');
str = str.replace(regEx,"").toLowerCase();
if(str == reverse(str)) {
return true;
}
else {
return false;
}
}
That will work.
From the example given, it seems to me that the code doesn't work for spaces in between the letters. (There may be other scenarios as well)
I have changed this line :
str = str.replace(/[^a-zA-Z]+/,"").toLowerCase();
To this :
str = str.toLowerCase().replace(/[^a-z]/g,"");
change this line:
str = str.replace(/[^a-zA-Z]+/,"").toLowerCase();
to this:
str = str.toLowerCase().replace(/[^a-z0123456789]+/g,"");
This regex should work for your code.
/[^1-9a-zA-Z]+/g

Search for a whole word in a string

I am looking for a function written in JavaScript (not in jQuery) which will return true if the given word exactly matches (should not be case sensitive).
Like...
var searchOnstring = " Hi, how are doing?"
if( searchText == 'ho'){
// Output: false
}
if( searchText == 'How'){
// Output: true
}
You could use regular expressions:
\bhow\b
Example:
/\bhow\b/i.test(searchOnstring);
If you want to have a variable word (e.g. from a user input), you have to pay attention to not include special RegExp characters.
You have to escape them, for example with the function provided in the MDN (scroll down a bit):
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = '\\b';
regex += escapeRegExp(yourDynamicString);
regex += '\\b';
new RegExp(regex, "i").test(searchOnstring);
Here is a function that returns true with searchText is contained within searchOnString, ignoring case:
function isMatch(searchOnString, searchText) {
searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
}
Update, as mentioned you should escape the input, I'm using the escape function from https://stackoverflow.com/a/3561711/241294.
Something like this will work:
if(/\show\s/i.test(searchOnstring)){
alert("Found how");
}
More on the test() method
Try this:
var s = 'string to check', ss= 'to';
if(s.indexOf(ss) != -1){
//output : true
}

Categories