English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic JavaScript Practice: Reversing Strings and Palindromes

Reverse String

To reverse a string (Reverse a String) means to process the string in reverse order, for example, given a string "hello", the reversed should return "olleh".

Test Cases

  1. reverseString("hello") should return "olleh"
  2. reverseString("Greetings from Earth") should return "htraE morf sgniteerG"

Implementation Approach

The most convenient method is to convert the string into an array, reverse the array, and then convert it back into a string to return. You need to use the built-in methods of the string object and the array object:

  1. String.split()
  2. Array.reverse()
  3. Array.join()

You can see the JavaScript reference manual for the details

function reverseString(str) {
 return str.split('').reverse().join('');
}
reverseString("hello");

One line of return, isn't it very simple?!

Let's see how palindromes work on this basis &11015;65039;

Palindrome

"Madam, I'm Adam." This was the first sentence Adam said to Eve in the Garden of Eden. This sentence reads the same forwards and backwards, and such sentences are called Palindromes in English.

For example, the sentence 'Shanghai tap water comes from the sea' reads the same forwards and backwards. There are also many English words like Level, Madam, Radar, LOL (hahaha)...

Test Cases

  1. palindrome("Race Car") should return true
  2. palindrome("not a palindrome") should return false
  3. palindrome("0_0 (") /-\ :) 0-0) should return true

Implementation Approach

We need to write a method called palindrome() that takes a parameter called str. If str is a Palindrome, it will return true; otherwise, it will return false.

It should be noted that punctuation and spaces should be removed and then toUpperCase or toLowerCase before judgment.

The following knowledge points are needed:

  • Regular expression (regular expression) is used to filter symbols and spaces
  • String.replace() replaces substrings that match the regular expression
  • String.toLowerCase() converts a string to lowercase

About regular expressions

Here, it is required to match both uppercase and lowercase English letters and integers, and any punctuation and spaces will be filtered out. Therefore, you can use /any uppercase letter-Za-z0–9]/g or /[\W_]/g

  • any uppercase letter-Z] Matches any character that is not26any uppercase letter
  • any lowercase letter-z] Matches any character that is not26any lowercase letter
  • any number-9] Matches any character that is not from 0 to9any number
  • ^[^_] Matches any character that is not an underscore
  • ^ Matches the beginning of a string
  • \w Note that it is lowercase, matching letters or numbers or underscores or Chinese characters
  • \W Note that it is uppercase, matching any character that is not a letter, number, underscore, or Chinese character, equivalent to [^A-Za-z0-9_]
  • g represents global search

Here is my method:


 str = str.replace(/[\W_]/g,'').toLowerCase();
 var reverseStr = str.split('').reverse().join('');
 return str===reverseStr;
}
palindrome("eye");

I saw on the internet that it can also be implemented using a For loop:

function palindrome (str) {
 var reg = /[\W_]/g,
 regStr = str.toLowerCase().replace(reg, ''),
 len = regStr.length;
 for (var i = 0, halfLen = len / 2; i < halfLen; i++{
 if (regStr[i] !== regStr[len - 1 - i]) {
  return false;
 }
 }
 return true;
}

This approach cleverly uses the characteristics of palindromes, cutting the entire string in half, and then traversing it in a loop to judge whether the first and last characters are equal in sequence.

There is also an implementation using recursion:

function palindrome (str) {
 // Remove unnecessary characters from a string
 var re = /[\W_]/g;
 // Convert a string to lowercase
 var lowRegStr = str.toLowerCase().replace(re, '');
 // If the length of the string lowRegStr is 0, then the string is a palindrome
 if (lowRegStr.length === 0) {
 return true;
 }
 // If the first and last characters of the string are not the same, then the string is not a palindrome
 if (lowRegStr[0] !== lowRegStr[lowRegStr.length - 1)) {
 return false;
 } else {
 return palindrome(lowRegStr.slice(1, lowRegStr.length - 1));
 }
}

I feel that the other two implementation ideas are much cooler than mine. I have just started on the road to programming, so let's take it step by step.

By the way, don't worry about the difference between reversing a string and a palindrome! Reversing a string simply returns the string in reverse order; while a palindrome faces longer and more complex sentences, which need to compare whether the sentence after removing spaces and punctuation marks is equal to the reversed sentence.

Summary

That's all for this article. I hope the content of this article can bring a certain amount of help to everyone's learning or use of Javascript. If you have any questions, you can leave a message for communication. Thank you for your support of the Yelling tutorial.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like