byteSize
返回字符串的字节长度。
将给定的字符串转换为Blob Object
并查找其size
。
const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11
capitalize
字符串首字母大写。
使用数组解构和String.toUpperCase()
大写第一个字母,用...rest
获得第一个字母后的字符数组,然后用Array.join('')
将所得的数组合并为字符串。
如果lowerRest
参数为true
,将转变剩余字符串为小写输出,否则原样输出。
const capitalize = ([first, ...rest], lowerRest = false) =>
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'
capitalizeEveryWord
将字符串中每个单词的首字母大写。
用String.replace()
去匹配每个单词的首字母,然后用toUpperCase()
将该字母大写。
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!'
decapitalize
将一个字符串的第一个字母(大写字母)变成小写。
使用数组解构和String.toLowerCase()
将第一个字母变成小写,...rest
是获取第一个字母之后字符数组,然后使用Array.join('')
使其再次拼接成为字符串。 省略upperRest
参数来保持字符串的其余部分不变,或者将其设置为true
来将字符串的其余部分转换为大写。
const decapitalize = ([first, ...rest], upperRest = false) =>
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar', true); // 'fOOBAR'
escapeHTML
转义一个字符串,以用于HTML。
const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
escapeHTML('<a href="#">Me & you</a>');
// '<a href="#">Me & you</a>'
escapeRegExp
转义字符串以在正则表达式中使用。
使用String.replace()
来转义特殊字符。
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
escapeRegExp('(test)'); // \\(test\\)
fromCamelCase
转换驼峰字符串。
用replace()
以下划线,连字符和空格为分隔符转换驼峰形式的字符串,首先需要去除字符串中的分割字符,然后,用分隔符拼接字符串。
第二个参数默认为_
。
const fromCamelCase = (str, separator = '_') =>
str
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
.toLowerCase();
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
isAbsoluteURL
如果给定的字符串是绝对URL,则返回true
;否则返回false
。
使用正则表达式来测试字符串是否是绝对URL。
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false
isLowerCase
检查字符串是否小写。
将给定的字符串转换为小写,使用String.toLowerCase()
并将其与原始值进行比较。
const isLowerCase = str => str === str.toLowerCase();
isLowerCase('abc'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false
isUpperCase
检查一个字符串是否大写。
将给定的字符串转换为大写,使用String.toUpperCase()
并将其与原始值进行比较。
const isUpperCase = str => str === str.toUpperCase();
isUpperCase('ABC'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false
mask
用指定的掩码字符替换除最后num
个字符以外的所有字符。
使用String.slice()
获取需要被遮蔽的字符部分,并用正则表达式替换每个字符。 将遮蔽的字符与字符串的其余未遮蔽部分拼接起来。 省略第二个参数num
,默认值为4,也就是说最后4个字符不被遮蔽。 如果num
是负数,则不被遮蔽的字符将从字符串的开头算起。 省略第三个参数mask
,默认使用字符*
作为掩码遮蔽。
const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'
palindrome
如果给定的字符串是回文,则返回true
;否则返回false
。
使用toLowerCase()
转换字符串,并使用String.replace()
从中删除非字母数字字符。 然后,在将其转换为String.tolowerCase()
之后,将String.split('')
为单独的字符,Array.reverse()
,String.join('')
并与原始非反转字符串进行比较。
const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g, '');
return s === [...s].reverse().join('');
};
palindrome('taco cat'); // true
toCamelCase
字符串转化为驼峰形式的字符串。
用replace()
去移除下划线,连接符,空格,然后将字符串转化为驼峰形式输出。
const toCamelCase = str => {
let s =
str &&
str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join('');
return s.slice(0, 1).toLowerCase() + s.slice(1);
};
toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized'
toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');
// 'someMixedStringWithSpacesUnderscoresAndHyphens'
reverseString
反转字符串。
用split('')
和Array.reverse()
去反转字符数组中元素的顺序。
用join('')
去拼字符数组为字符串。
const reverseString = str => [...str].reverse().join('');
reverseString('foobar'); // 'raboof'
sortCharactersInString
按字符顺序排列字符串中字符的顺序。
用split('')
将字符串转化为数组,然后用Array.sort()
依据自定义排序规则localeCompare()
为字符数组排序,最后用join('')
重新拼接字符数组为字符串。
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
sortCharactersInString('cabbage'); // 'aabbceg'
truncateString
保留指定长度的字符串。
需要判断字符串的length
是否大于num
。
返回你希望的截断后的字符串, 尾部有....
。
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
truncateString('boomerang', 7); // 'boom...'
unescapeHTML
反转义HTML字符。
const unescapeHTML = str =>
str.replace(
/&|<|>|'|"/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
''': "'",
'"': '"'
}[tag] || tag)
);
unescapeHTML('<a href="#">Me & you</a>'); // '<a href="#">Me & you</a>'
URLJoin
将所有给定的URL段连接在一起,然后规范化生成的URL。
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
// 'http://www.google.com/a/b/cd?foo=123&bar=foo'
words
将字符串转化为以单词为元素的字符串数组,去除所有非单词元素。
用String.split()
以pattern
正则表达式为分割规则来分割字符串为字符串数组。用Array.filter()
移除字符串中的空字符。
默认pattern
为/[^a-zA-Z-]+/
。
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]