Skip to content

Commit cbcc4fa

Browse files
committed
feat: add urlJoin method
1 parent 3419b09 commit cbcc4fa

File tree

4 files changed

+63
-1
lines changed

4 files changed

+63
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## 1.3.3 (2024--)
44

55
- `objFindItemRecursiveByKey`: Add `objFindItemRecursiveByKey` method
6+
- `urlJoin`: Add `urlJoin` method
67

78
## 1.3.2 (2023-12-28)
89

docs/src/methods/string.md

+18
Original file line numberDiff line numberDiff line change
@@ -490,3 +490,21 @@ Converts the given string to ascii code and returns it as an array.
490490
```javascript
491491
_.strToAscii('12345'); // Returns [49, 50, 51, 52, 53]
492492
```
493+
494+
## `_.urlJoin`
495+
496+
Merges the given string argument with the first argument (the beginning of the URL), joining it so that the slash (`/`) symbol is correctly included.
497+
498+
### Parameters
499+
500+
- `args::string[]`
501+
502+
### Returns
503+
504+
> string
505+
506+
### Examples
507+
508+
```javascript
509+
_.urlJoin('https://example.com', 'hello', 'world'); // Returns 'https://example.com/hello/world'
510+
```

lib/index.ts

+25
Original file line numberDiff line numberDiff line change
@@ -836,6 +836,30 @@ export default class Qsu {
836836
return [...new Set(str)].join('');
837837
}
838838

839+
static urlJoin(...args: string[]): string {
840+
if (!args) {
841+
return '';
842+
}
843+
844+
const argLength = args.length;
845+
let urlResult = '';
846+
847+
for (let i = 0; i < argLength; i += 1) {
848+
if (
849+
i === 0 ||
850+
args[i].startsWith('/') ||
851+
args[i].startsWith('?') ||
852+
args[i].startsWith('&')
853+
) {
854+
urlResult += args[i];
855+
} else {
856+
urlResult += `/${args[i]}`;
857+
}
858+
}
859+
860+
return urlResult;
861+
}
862+
839863
/*
840864
* Verify
841865
* */
@@ -1096,6 +1120,7 @@ export const {
10961120
strToNumberHash,
10971121
strUnique,
10981122
strToAscii,
1123+
urlJoin,
10991124
isObject,
11001125
isEqual,
11011126
isEqualStrict,

test/string.spec.ts

+19-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ import {
2424
strToNumberHash,
2525
strUnique,
2626
strToAscii,
27-
objectId
27+
objectId,
28+
urlJoin
2829
} from '../dist';
2930

3031
describe('String', () => {
@@ -240,4 +241,21 @@ st`),
240241
assert.strictEqual(objectId().length, 24);
241242
done();
242243
});
244+
245+
it('urlJoin', (done) => {
246+
assert.strictEqual(
247+
urlJoin('https://example.com', 'hello', 'world'),
248+
'https://example.com/hello/world'
249+
);
250+
assert.strictEqual(
251+
urlJoin('https://example.com', '/hello', '/world', 'bye'),
252+
'https://example.com/hello/world/bye'
253+
);
254+
assert.strictEqual(
255+
urlJoin('example.com', '/hello', '/world', 'bye'),
256+
'example.com/hello/world/bye'
257+
);
258+
assert.strictEqual(urlJoin('hello', '/world', 'bye'), 'hello/world/bye');
259+
done();
260+
});
243261
});

0 commit comments

Comments
 (0)