JavaScript - RegExp toString 方法
JavaScript 中的 toString() 方法通常用于检索对象的字符串表示形式。对于正则表达式 (RegEx),RegExp.toString() 方法用于检索表示正则表达式的字符串。
在 JavaScript 中,string 是一种表示字符序列的数据类型。可以由字母、数字、符号、单词或句子组成。
语法
以下是 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));
//让我们转换为字符串
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));
//让我们转换为字符串
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

