TypeScript中的RegExp [英] RegExp in TypeScript

查看:52
本文介绍了TypeScript中的RegExp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在TypeScript中实现Regexp?

How can I implement Regexp in TypeScript?

我的例子:

var trigger = "2"
var regex = new RegExp('^[1-9]\d{0,2}$', trigger); // where I have exception in Chrome console

推荐答案

我认为您想在TypeScript中对RegExp进行 test ,因此您必须这样做:

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

您应该阅读 MDN参考-RegExp RegExp对象接受两个参数 pattern flags ,它们是可以为空的(可以省略/未定义).要测试您的正则表达式,您必须使用 .test()方法,而不要在RegExp的声明中传递要测试的字符串!

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

为什么测试+" ?由于TS中的 alert()接受字符串作为参数,因此最好以这种方式编写它.您可以在此处尝试完整的代码.

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

这篇关于TypeScript中的RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆