Notes on regular expressions (4)

Time:2021-3-6

Create auriParser

As a web development engineer, I am familiar with the following code:

$kw = $_GET['keyword']; // PHP
String kw = request.getParameter("keyword"); // JSP

For the back-end language, we can easily get aurlParameter values in the request. However, when we need to get the URL parameters in the front-end project, JS has no corresponding interface. Fortunately, we can do this by encapsulating some string operations.

Query examples

var str = "http://search.jd.com/search?keyword=ipad%20min3%E4%BF%9D%E6%8A%A4%E5%A5%97&enc=utf-8&qrst=1&rt=1&stop=1&stock=1#filter";

explain

There are different opinions on regular expression construction. So, 100 programmers have 100 kinds of writing, the author here is just from the round to say, throw a brick to attract jade.

String.matchmethod

The basic idea is to match and match from the target stringkeyAnd returns the value of the corresponding parameter. Using regular expression matching, loops can be eliminated.

/**
 *Query the key value corresponding to the URL string
 *@ param {[string]} name [key value name]
 *@ param {[string]} URL [url string]
 *@ return {[string]} [corresponding value]
 */
var query = function(name,url) {
    var pattern = new RegExp("[\?&#]" + name + "=([^&#]+)","gi");
    var ma = (url || location.search).match(pattern);
    var strArr;

    if (ma && ma.length > 0) {
        strArr = (ma[ma.length-1]).split("=");
        if (strArr && strArr.length > 1) {
            return strArr[1];
        }
        return ''
    }
    return '';
}

query("keyword",str)

The above method can basically meet the needs of daily use, let’s take a look at the implementation of other methods.

RegExp.execmethod

The extra information provided after each match can be used to manipulate strings more flexibly. Reasonable encapsulation of some methods and interface exposure to meet the needs of the project.

/**
 *Query the corresponding key value of URL string
 * @param url
 * @returns {{get: Function, keys: Function}}
 */
function query(url) {
    if (typeof url !== "string") return;

    var RE_URL   = /([^&=]+?)(?=(=|&|$|#))=([^&$#]*)?/gi;
    var RE_HTTP  = /(https?):\/\//;
    var ma       = null;
    var r        = {}
    var k,v;

    if (url.match(RE_HTTP)) {
        url = url.slice(url.indexOf('?')+1)
    } else {
        url = location.search;
    }

    while ((ma = RE_URL.exec(url)) !== null) {
        k = ma[1];
        v = ma[3];
        if (!r[k]) {
            r[k] = v
        }
    }
    return {
        get: function(key) {
            if (r[key]) return r[key];
            return "";
        },
        keys: function() {
            var keys = [];
            if ('keys' in {}) {
                keys = {}.keys(r)
            } else {
                for (var i in r) {
                    keys.push(i)
                }
            }
            return keys;
        }
    }
}

var q = query(str)
q.get("keyword") // ipad%20min3%E4%BF%9D%E6%8A%A4%E5%A5%97
q.keys() // ["keyword", "enc", "qrst", "rt", "stop", "stock"]

Regular expression writing is different from person to person, the above is just a rudiment, interested friends can be extended optimization. Welcome to express your opinions, exchange more and make progress together!

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]