How does js determine whether it is a palindrome string? This article will introduce to you how to use js to determine whether a string is a palindrome string. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First of all, let’s understandWhat is a palindrome string?
The palindrome string is that we read it from the beginning to the end, which is the same as reading it from the end to the beginning. Example: ABCBA.
Next we will introduce to you how to easily use JavaScript functions to determine whether a string is a palindrome string.
In fact, the logic of determining whether a string is a palindrome is very simple: just remove the special characters from the string and reverse the result. If the strings are equal (the filtered string and the reverse filtered string), then this string is a palindrome string. Isn’t it easy!
Let’s take a look at how JavaScript follows the above logic to achieve the effect.
1. Use basic functions for verification
Following the logic mentioned above, we only need to create a variable containing the string we need. First we convert all characters of the string to lower case version, then we remove special characters and finally compare the strings and if they are equal the function returns a boolean confirming it:
/** *定义判断给定字符串是否为回文的函数isPalindrome()。 * * @returns {Boolean} */ function isPalindrome(str){ var normalized = str.toLowerCase().match(/[a-z]/gi).reverse(); return normalized.join('') === normalized.reverse().join(''); }
So you can Use the cast isPalindrome method which provides a string as the first argument, this will return a boolean value that will note if it is:
if(isPalindrome("Go dog.")){ console.log("它是回文"); }else{ console.log("它不是回文"); }
2. Use a prototype Function to verify
If you want to determine if a string is a palindrome without providing it as the first argument to any function, as long as the variable is a string, you can pass Create a shortcut by extending the String prototype and creating your own function for it. In this way, you can call the isPalindrome method as if it were a property of the string, for example:
/** * 允许校验的字符串扩展函数 * 字符串是否为回文。 * * @returns {Boolean} */ String.prototype.isPalindrome = function () { var normalized = this.toLowerCase().match(/[a-z]/gi).reverse(); return normalized.join('') === normalized.reverse().join(''); }
Therefore, you can cast the string using the isPalindrome method, which will return a boolean value, Notice whether it:
if("Go dog.".isPalindrome()){ console.log("它是回文"); }else{ console.log("它不是回文"); }
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How does js determine whether it is a palindrome string?. For more information, please follow other related articles on the PHP Chinese website!