JavaScript 程序:检查字符串是否是回文

要理解此示例,您应了解以下 JavaScript 编程 主题


如果一个字符串从前向后读与从后向前读都相同,那么它就是一个回文。例如,dad 从前向后读都相同。所以单词dad 是一个回文。同样,madam 也是一个回文。


示例 1:使用 for 循环检查回文

// program to check if the string is palindrome or not

function checkPalindrome(string) {

    // find the length of a string
    const len = string.length;

    // loop through half of the string
    for (let i = 0; i < len / 2; i++) {

        // check if first and last string are same
        if (string[i] !== string[len - 1 - i]) {
            return 'It is not a palindrome';
        }
    }
    return 'It is a palindrome';
}

// take input
const string = prompt('Enter a string: ');

// call the function
const value = checkPalindrome(string);

console.log(value);

输出

Enter a string: madam
It is a palindrome

在上面的程序中,checkPalindrome() 函数接收用户的输入。

  • 使用 length 属性计算字符串的长度。
  • 使用 for 循环迭代字符串的一半。if 条件用于检查第一个字符和对应的最后一个字符是否相同。此循环一直执行到字符串的一半。
  • 在迭代过程中,如果字符串的任何字符与其对应的最后一个字符串不相等,则该字符串不被认为是回文。

示例 2:使用内置函数检查回文

// program to check if the string is palindrome or not

function checkPalindrome(string) {

    // convert string to an array
    const arrayValues = string.split('');

    // reverse the array values
    const reverseArrayValues = arrayValues.reverse();

    // convert array to string
    const reverseString = reverseArrayValues.join('');

    if(string == reverseString) {
        console.log('It is a palindrome');
    }
    else {
        console.log('It is not a palindrome');
    }
}

//take input
const string = prompt('Enter a string: ');

checkPalindrome(string);

输出

Enter a string: hello
It is not a palindrome

在上面的程序中,使用 JavaScript 中可用的 内置方法 来检查回文。

  • split('') 方法将字符串转换为单个 数组 字符。
    const arrayValues = string.split(''); // ["h", "e", "l", "l", "o"]
  • reverse() 方法会颠倒数组中元素的顺序。
    // ["o", "l", "l", "e", "h"]
    const reverseArrayValues = arrayValues.reverse();
  • join('') 方法将数组的所有元素连接成一个字符串。
    const reverseString = reverseArrayValues.join(''); // "olleh"
  • 然后使用 if...else 语句检查字符串和反转后的字符串是否相等。如果它们相等,则该字符串是回文。

注意:多行代码可以合并,写在一行中。

const reverseString = string.split('').reverse().join('');

另请阅读

在结束之前,让我们通过以下挑战来检验你对 JavaScript 编程检查字符串是否为回文的知识!你能解决下面的挑战吗?

挑战

编写一个函数来查找字符串是否为回文。

  • 回文是指一个字符串从前向后读与从后向前读都相同的字符串。例如:"radar""madam" 等。
  • 如果输入字符串是回文,则返回 true。否则,返回 false
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战