match-path-plus
match-path
Last updated 9 years ago by g120hbq .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install match-path-plus 
SYNC missed versions from official npm registry.

match-path-plus

Powered by path-to-regexp.

my love

Install

yarn add match-path-plus

import

//es6
import { matchPath , mapSearchParams } from 'match-path-plus'
//es5
const { matchPath , mapSearchParams } = require('match-path-plus')

Usage

//typescript
/**
 * entry
 */
import * as  pathToRegExp from 'path-to-regexp'

const cache = new Map()

/**
 * Converts path to a regex, if a match is found then we extract params from it
 * @param routePattern 
 * @param url 
 * @param regOptions path-to-regexp options
 */
export function matchPath(routePattern, url, regOptions) {
    const [pathToMatch = '/', search = ''] = url.split('?')
    let regexp = cache.get(routePattern)

    if (!regexp) {
        const keys = []
        // path-to-regexp options
        regOptions = {
            ...regOptions,
            sensitive: false,
            strict: false,
            end: false
        }
        regexp = { pattern: pathToRegExp(routePattern, keys, regOptions), keys }
        cache.set(routePattern, regexp)
    }

    const m = regexp.pattern.exec(pathToMatch)

    if (!m) {
        return null
    }

    const path = m[0]
    const params = Object.create(null)

    for (let i = 1; i < m.length; i += 1) {
        params[regexp.keys[i - 1].name] = decodeURIComponent(m[i])
    }

    // Add querystring params
    Object.assign(params, mapSearchParams(search))

    return {
        path: path === '' ? '/' : path,
        params
    }
}

/**
 * Maps a querystring to an object
 * Supports arrays and utf-8 characters
 * @param search
 * @returns {any}
 */
export function mapSearchParams(search) {
    let params = {}
    let params_re = /([^?&=]+)=?([^&]*)/g

    if (search.indexOf('?') !== -1) {
        search = search.split('?')[1]
    }

    search.replace(params_re, function (m, name, value) {
        params[decodeURIComponent(name)] = decodeURIComponent(value)
    })

    return params
}

Current Tags

  • 0.0.3                                ...           latest (9 years ago)

3 Versions

  • 0.0.3                                ...           9 years ago
  • 0.0.2                                ...           9 years ago
  • 0.0.1                                ...           9 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 1
Dependencies (2)
Dev Dependencies (9)
Dependents (1)

Copyright 2013 - present © cnpmjs.org | Home |