JavaScript - RegExp toString 方法



在 JavaScript 中,toString() 方法通常用於檢索物件的字串表示形式。對於正則表示式 (RegEx),RegExp.toString() 方法檢索表示正則表示式的字串。

在 JavaScript 中,字串是一種資料型別,表示字元序列。它可以由字母、數字、符號、單詞或句子組成。

語法

以下是 JavaScript RegExp.toString() 方法的語法:

RegExp.toString()

引數

  • 它不接受任何引數。

返回值

此方法返回一個字串,表示給定的物件(或正則表示式)。

示例

示例 1

在下面的示例中,我們使用 JavaScript RegExp.toString() 方法來檢索表示此正則表示式 "[a-zA-Z]" 的字串。

<html>
<head>
   <title>JavaScript RegExp.toString() Method</title>
</head>
<body>
   <script>
      const regex = new RegExp("^[a-zA-Z\\s]*$");
      document.write("The regex: ", regex);
      document.write("<br>Type of regex: ", typeof(regex));
      
      //lets convert to string
      const result = regex.toString();
      document.write("<br>String representing of this regex: ", result);
      document.write("<br>Type of result: ", typeof(result));
   </script>
</body>
</html>

輸出

上述程式返回表示此正則表示式的字串為:

The regex: /^[a-zA-Z\s]*$/
Type of regex: object
String representing of this regex: /^[a-zA-Z\s]*$/
Type of result: string

示例 2

如果當前正則表示式物件為空,此方法將返回 "/(?:)/"

以下是 JavaScript RegExp.toString() 方法的另一個示例。我們使用此方法來檢索表示此空正則表示式 ("") 的字串。

<html>
<head>
   <title>JavaScript RegExp.toString() Method</title>
</head>
<body>
   <script>
      const regex = new RegExp("");
      document.write("The regex: ", regex);
      document.write("<br>Type of regex: ", typeof(regex));
      
      //lets convert to string
      const result = regex.toString();
      document.write("<br>String representing of this regex: ", result);
      document.write("<br>Type of result: ", typeof(result));
   </script>
</body>
</html>

輸出

執行上述程式後,它將返回 "/(?:)/"。

The regex: /(?:)/
Type of regex: object
String representing of this regex: /(?:)/
Type of result: string
廣告