當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


JavaScript 正則 \s用法及代碼示例


JavaScript 中的 RegExp \s 元字符用於查找空白字符。空白字符可以是空格/製表符/換行符/垂直字符。它與 [ \t\n\r] 相同。語法:

/\s/ 

或者

new RegExp("\\s")

帶修飾符的語法:

/\s/g 

或者

new RegExp("\\s", "g")

範例1:此示例用破折號替換空格。



html


<!DOCTYPE html>
<html>
 
<head>
    <title>
        JavaScript RegExp \s Metacharacter
    </title>
</head>
 
<body style="text-align:center">
     
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
     
    <h2>RegExp \s Metacharacter</h2>
     
     
<p>
        Input String:GeeksforGeeks is the computer
        science\nportal\tfor geeks.
    </p>
 
     
    <button onclick="geek()">
        Click it!
    </button>
     
    <p id="app"></p>
 
     
    <script>
        function geek() {
            var regex = /\s/g;
            var replace = "-";
            var str = "GeeksforGeeks is the computer "
                    + "science\nportal\tfor geeks.";
            var str1 = str.replace(regex, replace);
            alert("The new string is:\n" + str1);
        }
    </script>
</body>
 
</html>                   

輸出:
單擊按鈕之前:

backs

單擊按鈕後:

backs

範例2:本示例將所有空格替換為 hash(#)。

html


<!DOCTYPE html>
<html>
 
<head>
    <title>
        JavaScript RegExp \s Metacharacter
    </title>
</head>
 
<body style="text-align:center">
     
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
     
    <h2>RegExp \s Metacharacter</h2>
     
     
<p>
        Input String:Geeks Classes is a Classroom
        programme by GeeksforGeeks to enhance DSA.
    </p>
 
     
    <button onclick="geek()">
        Click it!
    </button>
     
    <p id="app"></p>
 
     
    <script>
        function geek() {
            var regex = new RegExp("\\s", "g");
            var replace = "#";
            var str = "Geeks Classes is a Classroom "
                    + "programme\nby GeeksforGeeks\tto"
                    + " enhance DSA";
            var str1 = str.replace(regex, replace);
            alert("The new string is:\n" + str1);
        }
    </script>
</body>
 
</html>                   

輸出:
單擊按鈕之前:

backs

單擊按鈕後:

backs

支持的瀏覽器:下麵列出了 RegExp \s Metacharacter 支持的瀏覽器:

  • 穀歌瀏覽器
  • 蘋果Safari
  • 火狐瀏覽器
  • Opera
  • IE瀏覽器




相關用法


注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 JavaScript | RegExp \s Metacharacter。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。