JavaScript 增加/减少字母

JavaScript 增加/减少字母

任务是使用ASCII值来增加/减少字母,借助于JavaScript

方法:

  • 使用charCodeAt()方法来返回字符串中指定索引处字符的Unicode值。
  • 根据需求增加/减少ASCII值。
  • 使用fromCharCode()方法将Unicode值转换为字符。

示例1: 在这个示例中,点击按钮会将字符’a’增加。

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
          Click on the button to 
        increment the letter
      </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to 
        increment the letter.
    </p>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <p id="GFG"></p>
 
    <script>
        var down = document.getElementById('GFG');
 
        down.innerHTML = 'a';
 
        function nextCharacter(c) {
            return String.fromCharCode(c.charCodeAt(0) + 1);
        }
 
        function GFG_Fun() {
            let c = down.innerHTML;
            down.innerHTML = nextCharacter(c);
        }
    </script>
</body>
 
</html>

输出:

JavaScript 增加/减少字母

示例2: 在这个示例中,通过点击按钮来递减字符’z’。

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Click on the button to 
        decrement the letter
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to 
        decrement the letter.
    </p>
 
    <button onclick="GFG_Fun()">
        click here
    </button>
 
    <p id="GFG"></p>
 
    <script>
        var down = document.getElementById('GFG');
 
        down.innerHTML = 'z';
 
        function nextCharacter(c) {
            return String.fromCharCode(c.charCodeAt(0) - 1);
        }
 
        function GFG_Fun() {
            let c = down.innerHTML;
            down.innerHTML = nextCharacter(c);
        }
    </script>
</body>
 
</html>

输出:

JavaScript 增加/减少字母

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程