简体   繁体   中英

Regex to Match Specific URL JavaScript

I'm trying to match a specific URL( http://www.example.me/area/?si= ) that allows me to get value from si. si value will be dynamic

http://www.example.me/area/?si=4077765

Assuming that the value of the si key in the query string will always be digits (ie: 0 - 9), try this...

var url = 'http://www.example.me/area/?test=4894&si=4077765&f=fjjjf',
    si = url.match(/.*[\?&]si=(\d+)/i)[1];

or a little more generic...

function getQueryStringValue(url, key) {
    var regex = new RegExp('.*[\\?&]' + key + '=(\\d+)', 'i');
    return url.match(regex)[1];
}

if not digits try this...

/.*[\?&]si=(\w+)/i

Explanation:

  • .* matches any character (except newline) between 0 and unlimited times
  • [\\?&] match a single character, either ? or &
  • si= matches the characters si= literally (case insensitive)
  • (\\d+) first capturing group. matches any digit [0-9] between 1 and unlimitted times
  • i modifier - case insensitive

regex101

Get any query string value

function qstr(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] == variable) { return pair[1]; } } return false; }

Check Query String Exists

function isset_qstr(field) { var url = vp_furl(); if (url.indexOf('?' + field + '=') != -1) { return true; } else if (url.indexOf('&' + field + '=') != -1) { return true; } return false; }

I think you need the first function. Vote up if you think its helpful.

Thank you. Good Luck

Something like that can do the trick I think:

var regex = /http\:\/\/www\.example\.me\/area\/\?si=(\w*)/;

var url = 'http://www.example.me/area/?si=4077765';
var si = url.match(regex)[1]; // si = '4077765'

The first part of the regex is simply your URL "\\" is used to escape special characters.

(\\d+) is a capturing group that matches all character from az, AZ, 0-9, including the _ (underscore) character from 0 to n iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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