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
Type of regex: object
String representing of this regex: /^[a-zA-Z\s]*$/
Type of result: string
示例 2
如果当前 regex 对象为空,该方法将返回 “/(?:)/”。
以下是 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
Type of regex: object
String representing of this regex: /(?:)/
Type of result: string