如果我这样做:最好的方式来获得正则表达式的字符串表示从正则表达式字面
// note that \x1f is a control character
var regex = new RegExp("\x1f");
// prints "//"
console.log(regex.toString());
如果我不是这样做:
var regex = /\\x1f/;
// prints "/\\x1f/"
console.log(regex.toString());
我希望能够得到第一结果(//
- 带控制字符的字符串)来自第二个正则表达式。有没有简单的方法来做到这一点?到目前为止,我只能够令人作呕eval
黑客要做到这一点:
var regexValue = /\\x1f/.toString();
let escapedLiteral = regexValue
// turn double backslashes (\\) into single backslashes (\),
.replace(/\\\\/g, '\\')
// remove the opening and closing forward slashes (/).
// this needs to be more intelligent - what if there are flags?
.slice(1, -1);
// there could be an invalid regular expression string
try {
regexValue = eval('new RegExp("' + escapedLiteral + '")').toString();
} catch (e) {
regexValue = null;
}
// should print "//"
document.writeln(regexValue);
我正在做一些JavaScript源代码解析的,这种不同使事情变得具有挑战性。
你试过.source? – YOU
@YOU它看起来像'.source'与'.toString()'有相同的结果。 –