JS Code block 代码块–String 字符串

星期一, 2023-04-17 | Author: Lee | computer, 前端 | 228 views

String 字符串
去除空格
字符大小写转换
翻转字符
下划线格式字符串转为驼峰格式
驼峰格式字符串转为下划线格式
转义html(防XSS攻击)

/**
 * 去除空格
 * @param  {str}
 * @param  {type} :  1-所有空格  2-前后空格  3-前空格 4-后空格
 * @return {String}
 */
function trim (str, type) {
    type = type || 1
    switch (type) {
        case 1:
            return str.replace(/\s+/g, "");
        case 2:
            return str.replace(/(^\s*)|(\s*$)/g, "");
        case 3:
            return str.replace(/(^\s*)/g, "");
        case 4:
            return str.replace(/(\s*$)/g, "");
        default:
            return str;
    }
}
 
/**
 * 字符大小写转换
 * @param  {str}
 * @param  {type}:  1:首字母大写  2:首页母小写  3:大小写转换  4:全部大写  5:全部小写
 * @return {String}
 */
function changeCase (str, type) {
    type = type || 4
    switch (type) {
        case 1:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
 
            });
        case 2:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
            });
        case 3:
            return str.split('').map( function(word){
                if (/[a-z]/.test(word)) {
                    return word.toUpperCase();
                }else{
                    return word.toLowerCase()
                }
            }).join('')
        case 4:
            return str.toUpperCase();
        case 5:
            return str.toLowerCase();
        default:
            return str;
    }
}
 
/**
 * @name 翻转字符
 * @param {string} [text=""] 字符
 */
function ReverseText(text = "") {
	return text.split("").reduceRight((t, v) => t + v);
}
 
/**
 * 下划线格式字符串转为驼峰格式
 * @param {string} text处理前字符串
 * @return {string} 处理后的字符串
 * @runkit true
 * @example
 * toCamelCase('to_camel_case')
 * // 'toCamelCase'
 */
function toCamelCase(str) {
    return str.replace(/\_[a-z]/g, function (item) {
        return item[1].toUpperCase();
    });
}
 
/**
 * 驼峰格式字符串转为下划线格式
 * @param {string} text处理前字符串
 * @return {string} 处理后的字符串
 */
function toSnakeCase(str) {
    return str.replace(/[A-Z]/g, function (item) {
        return "_" + item[0].toLowerCase();
    });
}
 
/**
 * 转义html(防XSS攻击)
 * @param str 字符串
 */
function escapeHTML (str) {
    return     str.replace(
        /[&<>'"]/g,
        tag =>
            ({
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                "'": '&#39;',
                '"': '&quot;'
            }[tag] || tag)
    );
}

Tags:

文章作者: Lee

本文地址: https://www.pomelolee.com/2371.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta