-
Notifications
You must be signed in to change notification settings - Fork 0
/
substr.ts
64 lines (63 loc) · 1.73 KB
/
substr.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @packageDocumentation
* @module @tomato-js/string
*/
interface SubstringOptions {
itself: boolean;
}
/**
* 截取匹配到的字符后面的内容
*
* 脚本举例
* ```
* import { substringFromChar } from '@tomato-js/string'
* const str = substringFromChar('hello world','l');//'lo world'
* const str = substringFromChar('hello world','l',{itself:true});//'llo world'
* ```
*
* @param string - 原来的字符串
* @param char - 标识字符
* @param options - 其他参数
* @param options.itself - 截取的字符串是否包含char本身,默认为false
* @returns 截取后的字符串
*/
export function substringFromChar(
string: string,
char: string,
options: SubstringOptions = {
itself: false
}
) {
const { itself } = options;
if (string.indexOf(char) === -1) return "";
const indexOfChar = itself ? string.indexOf(char) : string.indexOf(char) + 1;
return string.substring(indexOfChar);
}
/**
* 截取匹配到的字符前面的内容
*
* 脚本举例
* ```
* import { substringToChar } from '@tomato-js/string'
* const str = substringToChar('hello world','l');//'he'
* const str = substringToChar('hello world','l',{itself:true});//'hel'
* ```
*
* @param string - 原来的字符串
* @param char - 标识字符
* @param options - 其他参数
* @param options.itself - 截取的字符串是否包含char本身,默认为false
* @returns 截取后的字符串
*/
export function substringToChar(
string: string,
char: string,
options: SubstringOptions = {
itself: false
}
) {
const { itself } = options;
if (string.indexOf(char) === -1) return "";
const indexOfChar = itself ? string.indexOf(char) + 1 : string.indexOf(char);
return string.substring(0, indexOfChar);
}