这个RegExp不应该工作吗? [英] Shouldn't this RegExp work?

查看:66
本文介绍了这个RegExp不应该工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

testString = "something://something/task?type=Checkin";

patt = new RegExp("something\/(\w*)\?");
match = patt.exec(testString);
document.querySelector('#resultRegexp').innerHTML = match[1];

我想捕获任务所以应该'这个RegExp有效吗?

I want to capture task So shouldn't this RegExp work?

我抓住任何字母数字字符直到问号...并捕获它。

I am grabbing any alphanumeric character up until the question mark... and capturing it.

http://jsfiddle.net/h4yhc/2/

推荐答案

你需要转义正则表达式文字中的斜杠,以及你创建正则表达式的字符串文字中的反斜杠:

You would need to escape the slash in regex literals, and the backslash in string literals which you create regexes from:

var patt = /something\/(\w*)\?/g;
// or
var patt = new RegExp("something/(\\w*)\\?", 'g');

我强烈推荐第一个版本,它更具可读性。

I strongly recommend the first version, it is more readable.

这篇关于这个RegExp不应该工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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