gpt4 book ai didi

javascript - 如何在javascript中使用正则表达式生成包含正斜杠的字符串?

转载 作者:行者123 更新时间:2023-11-30 12:55:36 24 4
gpt4 key购买 nike

我正在使用以下 Javascript 生成字符串:/abc/.source。通过在控制台中运行此代码,它将返回 "abc"

现在我想生成一个类似"abc/" 的字符串。

我试过 /abc\//.source 但它返回 "abc\/"

如何在不使用 var reg = new RegExp("abc/");reg.source 的情况下实现这一点?

最佳答案

我认为你误解了 source 属性:

Let S be a String in the form of a Pattern equivalent to P, in which certain characters are escaped as described below. S may or may not be identical to P or pattern; however, the internal procedure that would result from evaluating S as a Pattern must behave identically to the internal procedure given by the constructed object's [[Match]] internal property.

15.10.4.1 new RegExp(pattern, flags)

换句话说,源值必须能够用作正则表达式构造函数中的字符串:

var re = new RegExp( s.source );

匹配中使用时,结果表达式的行为必须与原始表达式相同。

因此假设要匹配 'abc/' 所需的模式是 abc\/ 然后 /abc\//.source 必须是 abc\/

顺便说一句:

(new RegExp('abc/')).source == 'abc\/';

关于javascript - 如何在javascript中使用正则表达式生成包含正斜杠的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com