nicecode-v2/packages/func/src/string/index.ts

81 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

///<summary>获得字符串实际长度中文2英文1</summary>
///<param name="str">要获得长度的字符串</param>
export const getStrLength = function (str: string) {
var realLength = 0,
len = str.length,
charCode = -1;
for (var i = 0; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128) realLength += 1;
else realLength += 2;
}
return realLength;
};
//js截取字符串中英文都能用
//如果给定的字符串大于指定长度,截取指定长度返回,否者返回源字符串。
//字符串,长度
/**
* js截取字符串中英文都能用
* @param str需要截取的字符串
* @param len: 需要截取的长度
*/
export const cutStr = function cutstr(str: string, len: number) {
var str_length = 0;
var str_len = 0;
let str_cut = new String();
str_len = str.length;
for (var i = 0; i < str_len; i++) {
let a = str.charAt(i);
str_length++;
if (escape(a).length > 4) {
//中文字符的长度经编码之后大于4
str_length++;
}
str_cut = str_cut.concat(a);
if (str_length >= len) {
str_cut = str_cut.concat('...');
return str_cut;
}
}
//如果给定字符串小于指定长度,则返回源字符串;
if (str_length < len) {
return str;
}
};
/**
* 查看字符串是否为可访问链接
* @param str 待检查链接
* @returns
*/
export const isUrl = (str: string) => {
try {
new URL(str);
return true;
} catch (err) {
return false;
}
}
/**
* 通过url获取值
* @param key 想要获取的值
* @param url 需要截取的链接
*/
export const getValueByUrl = (key: string, str: string) => {
let result = null
if (isUrl(str)) {
result = new URL(str).searchParams.get(key)
} else {
result = new URLSearchParams(str.indexOf('?') > -1 ? str : `?${str}`).get(key)
}
return result
}