简体   繁体   English

使用正则表达式匹配字符串

[英]Match a string using a regular expression

I have the following string 我有以下字符串

name=cvbb&source=Mamma+Mia&startdate=2014-03-24

How can I match the value associated with name with regular expressions, namely the string "cvbb" 如何将与名称关联的值与正则表达式匹配,即字符串“ cvbb”

/[^name] =[^&] / matches =cvbb but i want only cvbb / [^ name] = [^&] /匹配= cvbb,但我只想要cvbb

It looks like you want to get URL parameter value? 好像要获取URL参数值? In this case you could use this function : 在这种情况下,您可以使用以下功能:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var value = getParameterByName('startdate');

That would put 2014-03-24 in a var named value 这会将2014-03-24放入一个名为value

I am assuming you want to select the name out, right? 我假设您想选择名称,对不对? For that you can use the expression:- 为此,您可以使用以下表达式:

/name=([\w]+)&source=.*/

Explanation: The first word name is written right there. 说明:第一个单词的名称就写在这里。 After that ([\\w]+) will match a list of alphanumeric characters. 之后([\\ w] +)将匹配一个字母数字字符列表。 Then & will come and stop our selection. 然后&将停止我们的选择。 If you want to check that the string starts with name then use 如果要检查字符串以名称开头,请使用

/^name=([\w]+)&source=.*/

Caution: Using [^name] means that the characters should not be n,a,m or e which is not what you want to check. 注意:使用[^ name]表示字符不应为n,a,m或e,这不是您要检查的字符。 I hope this helps. 我希望这有帮助。

try 尝试

var queryString = 'name=cvbb&source=Mamma+Mia&startdate=2014-03-24';
var theStringImAfter = queryString.match(/[?&]name=([^&]*)/i)[1]

Note that queryString can be a full url eg from window.location.href, you don't need to parse the query string first. 请注意,queryString可以是完整的URL,例如来自window.location.href,您不需要首先解析查询字符串。

If you are passing an encoded string (which is the norm if you are including characters not supported in a url such as a space, ampersand or equal sign etc.) you will want to decode the string before you use it. 如果要传递编码的字符串(这是正常的情况,如果您包含URL中不支持的字符,例如空格,“&”或等号等),则需要在使用该字符串之前对其进行解码。 This can be done with decodeURIComponent(theStringImAfter) . 这可以通过decodeURIComponent(theStringImAfter)

Here is the same approach wrapped up in a reusable function 这是包含在可重用函数中的相同方法

function getArg(url, arg){
    var v=url.match(new RegExp('[?&]' + arg + '=([^&]*)', 'i'));
    return (v)?decodeURIComponent(v[1]):'';
}

Usage: 用法:

var theStringImAfter = getArg('name=cvbb&source=Mamma+Mia&startdate=2014-03-24', 'name');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM