Skip to content

Commit

Permalink
feat(url): 增加url的一些方法
Browse files Browse the repository at this point in the history
  • Loading branch information
novlan1 committed Apr 7, 2022
1 parent 476a61e commit 30207f2
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from './css'
export * from './wecom-robot'
export * from './function'
export * from './object'
export * from './url'
78 changes: 78 additions & 0 deletions src/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* url参数变数组
* @param {*} url
* @returns {Object} search对象
*
* @example
```ts
const res = getQueryObj('https://igame.qq.com?name=mike&age=18&feel=cold&from=china');
/**
* {
* name: 'mike',
* age: '18',
* feel: "cold",
* from: 'china',
* }
* /
```
*/
export function getQueryObj(url) {
const query = {}

let qs = url.substr(url.indexOf('?') > -1 ? url.indexOf('?') + 1 : url.length)
let kvs

qs = qs.split('&')
qs.forEach(item => {
kvs = item.split('=')
if (kvs.length === 2) {
const value = kvs[1]
query[kvs[0]] = value
}
})

return query
}

/**
* 组装`url`参数,将search参数添加在后面
* @param {string} url
* @param {Object} queryObj
* @returns {string} 组装后的url
*
* @example
```ts
const res = composeUrlQuery('https://baidu.com', {
name: 'mike',
feel: "cold",
age: '18',
from: 'test',
});
// https://baidu.com?name=mike&feel=cold&age=18&from=test
const res = composeUrlQuery('https://baidu.com?gender=male', {
name: 'mike',
feel: "cold",
age: '18',
from: 'test',
});
// https://baidu.com?gender=male&name=mike&feel=cold&age=18&from=test
```
*/
export function composeUrlQuery(url, queryObj) {
const oriQuery = getQueryObj(url)
let pathname = url.substr(
0,
url.indexOf('?') > -1 ? url.indexOf('?') : url.length,
)
pathname += '?'
const allQuery = {
...oriQuery,
...queryObj,
}
Object.keys(allQuery).forEach(i => {
pathname += `${i}=${allQuery[i]}&`
})
return pathname.substr(0, pathname.length - 1)
}
38 changes: 38 additions & 0 deletions test/url.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { getQueryObj, composeUrlQuery } from '../src'

describe('getQueryObj', () => {
it('', () => {
expect(
getQueryObj('https://igame.qq.com?name=mike&age=18&feel=cold&from=china'),
).toEqual({
name: 'mike',
age: '18',
feel: 'cold',
from: 'china',
})
})
})

describe('composeUrlQuery', () => {
it('', () => {
expect(
composeUrlQuery('https://baidu.com', {
name: 'mike',
feel: 'cold',
age: '18',
from: 'test',
}),
).toBe('https://baidu.com?name=mike&feel=cold&age=18&from=test')
})

it('already has query', () => {
expect(
composeUrlQuery('https://baidu.com?gender=male', {
name: 'mike',
feel: 'cold',
age: '18',
from: 'test',
}),
).toBe('https://baidu.com?gender=male&name=mike&feel=cold&age=18&from=test')
})
})

0 comments on commit 30207f2

Please sign in to comment.