卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章69207本站已运行4221

用于字符串、对象、数组和日期的常见 JavaScript 实用函数

用于字符串、对象、数组和日期的常见 javascript 实用函数

查看原帖并阅读目录

通过完整的 react 训练营学习 react,每年仅需 49 美元(免费试用 1 个月) *附属链接


实用函数就像代码的快捷方式。它们使您可以处理数组、日期和字符串等内容,而无需编写大量额外代码。您可以使用这些功能更快、一致地完成工作并防止错误,而不是一遍又一遍地执行相同的任务。

在本文中,我们将介绍每个开发人员都应该了解的 37 个常见 javascript 实用函数。如果您是 javascript 新手或尚未记录自己的实用函数,那么本文适合您。通过学习和使用这些实用程序,您将节省时间、减少错误,并更深入地了解如何编写干净、可重用的代码。

立即学习“Java免费学习笔记(深入)”;

相关帖子

  1. 20 个你可能不知道的鲜为人知的 javascript 功能
  2. javascript 数组/对象解构解释

那么,让我们开始吧,看看这些实用程序如何使您的 javascript 编码变得更轻松、更有效。

javascript 中的常用字符串工具

当然可以!以下是用于处理字符串的常见 javascript 实用函数的列表,每个函数都有简短的说明和示例用法:

1. 修剪

删除字符串两端的空格。

function trim(str) {
    return str.trim();
}

// example usage
console.log(trim('  hello world!  ')); // 'hello world!'

2. 大写

将字符串的第一个字母大写。

function capitalize(str) {
    return str.charat(0).touppercase() + str.slice(1);
}

// example usage
console.log(capitalize('hello')); // 'hello'

3. 转换为驼峰式大小写

将带有连字符的字符串转换为驼峰式大小写(camelcase)。

function tocamelcase(input) {
    return (
        input
            // replace kebab-case, snake_case, and spaces with a space
            .replace(/[-_s]+(.)?/g, (_, char) => (char ? char.touppercase() : ''))
            // handle pascalcase
            .replace(/^[a-z]/, (char) => char.tolowercase())
    );
}

// test cases
console.log(tocamelcase('pascalcase')); // pascalcase
console.log(tocamelcase('kebab-case-string')); // kebabcasestring
console.log(tocamelcase('snake_case_string')); // snakecasestring
console.log(tocamelcase('string with spaces')); // stringwithspaces

4. 转换为kebab大小写

将字符串转换为烤肉串大小写(kebab-case)。

function tokebabcase(input) {
    return (
        input
            // handle camelcase and pascalcase by inserting a dash before uppercase letters
            .replace(/([a-z])([a-z])/g, '$1-$2')
            // replace underscores and spaces with dashes
            .replace(/[_s]+/g, '-')
            // convert the entire string to lowercase
            .tolowercase()
    );
}

// test cases
console.log(tokebabcase('camelcase')); // camel-case
console.log(tokebabcase('pascalcase')); // pascal-case
console.log(tokebabcase('snake_case_string')); // snake-case-string
console.log(tokebabcase('string with spaces')); // string-with-spaces

5. 转换为蛇形格式

将字符串转换为蛇形大小写(snake_case)。

function tosnakecase(input) {
    return (
        input
            // handle camelcase and pascalcase by inserting an underscore before uppercase letters
            .replace(/([a-z])([a-z])/g, '$1_$2')
            // replace dashes and spaces with underscores
            .replace(/[-s]+/g, '_')
            // convert the entire string to lowercase
            .tolowercase()
    );
}

// test cases
console.log(tosnakecase('camelcase')); // camel_case
console.log(tosnakecase('pascalcase')); // pascal_case
console.log(tosnakecase('kebab-case-string')); // kebab_case_string
console.log(tosnakecase('string with spaces')); // string_with_spaces

6. 转换为帕斯卡大小写

将字符串转换为帕斯卡大小写(pascalcase)。

function topascalcase(input) {
    return (
        input
            // replace camelcase, kebab-case, snake_case, and spaces with a space
            .replace(/([a-z])([a-z])|[-_s]+(.)?/g, (match, p1, p2, p3) => {
                if (p2) {
                    return p1 + ' ' + p2;
                }
                return p3 ? ' ' + p3.touppercase() : '';
            })
            // split by space, capitalize first letter of each word, and join
            .split(' ')
            .map((word) => word.charat(0).touppercase() + word.slice(1).tolowercase())
            .join('')
    );
}

// test cases
console.log(topascalcase('camelcase')); // camelcase
console.log(topascalcase('kebab-case-string')); // kebabcasestring
console.log(topascalcase('snake_case_string')); // snakecasestring
console.log(topascalcase('string with spaces')); // stringwithspaces

7. 检查字符串是否包含另一个字符串

检查字符串是否包含指定的子字符串。

function contains(str, substring) {
    return str.indexof(substring) !== -1;
}

// example usage
console.log(contains('hello world', 'world')); // true

8. 替换所有出现的情况

替换字符串中所有出现的子字符串。

function replaceall(str, find, replace) {
    return str.split(find).join(replace);
}

// example usage
console.log(replaceall('hello world', 'o', 'a')); // 'hella warld'

9. 垫启动

用另一个字符串填充一个字符串的开头,直到达到目标长度。

function padstart(str, targetlength, padstring) {
    return str.padstart(targetlength, padstring);
}

// example usage
console.log(padstart('5', 3, '0')); // '005'

10. 垫端

用另一个字符串填充一个字符串的末尾,直到达到目标长度。

function padend(str, targetlength, padstring) {
    return str.padend(targetlength, padstring);
}

// example usage
console.log(padend('5', 3, '0')); // '500'

11. 计算字符出现的次数

计算字符在字符串中出现的次数。

function countoccurrences(str, char) {
    return str.split(char).length - 1;
}

// example usage
console.log(countoccurrences('hello world', 'o')); // 2

12. 转义 html

转义 html 特殊字符以防止 xss 攻击。

function escapehtml(str) {
    return str.replace(/[&"']/g, function (match) {
        const escapechars = {
            '&': '&',
            '': '>',
            '"': '"',
            "'": '''
        };
        return escapechars[match];
    });
}

// example usage
console.log(escapehtml('<div>"hello" &amp; 'world'</div>'));
// '<div>"hello" &amp; 'world'</div>'

13. 取消转义 html

转义 html 特殊字符。

function unescapehtml(str) {
    return str.replace(/&amp;||"|'/g, function (match) {
        const unescapechars = {
            '&amp;': '&amp;',
            '': '&gt;',
            '"': '"',
            ''': "'"
        };
        return unescapechars[match];
    });
}

// example usage
console.log(unescapehtml('<div>"hello" &amp; 'world'</div>'));
// '<div>"hello" &amp; 'world'</div>'

14.格式化货币

将数字格式化为货币字符串,用逗号作为千位分隔符。

function formatmoney(amount, decimalcount = 2, decimal = '.', thousands = ',') {
    try {
        // ensure the amount is a number and fix the decimal places
        decimalcount = math.abs(decimalcount);
        decimalcount = isnan(decimalcount) ? 2 : decimalcount;

        const negativesign = amount  3 ? i.length % 3 : 0;

        return (
            negativesign +
            (j ? i.substr(0, j) + thousands : '') +
            i.substr(j).replace(/(d{3})(?=d)/g, '$1' + thousands) +
            (decimalcount
                ? decimal +
                    math.abs(amount - i)
                        .tofixed(decimalcount)
                        .slice(2)
                : '')
        );
    } catch (e) {
        console.log(e);
    }
}

// test cases
console.log(formatmoney(1234567.89)); // 1,234,567.89
console.log(formatmoney(1234567.89, 3)); // 1,234,567.890
console.log(formatmoney(-1234567.89, 2, '.', ',')); // -1,234,567.89
console.log(formatmoney(1234567.89, 0, '.', ',')); // 1,234,568
console.log(formatmoney(1234.56, 2, ',', '.')); // 1.234,56

15. 截断段落

将段落截断为指定长度,并在截断时添加省略号。

function truncateparagraph(paragraph, maxlength) {
    if (paragraph.length 



<p>如果您想要截断字符串用于样式目的,您可以使用 tailwind<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15716.html" target="_blank">css</a> truncate / line-clamp 来完成此操作</p>

<h2>
  
  
  javascript 中的常见对象实用程序
</h2>

<h3>
  
  
  16. 检查一个值是否是一个对象
</h3>

<p>检查一个值是否是一个对象。<br></p>

<pre class="brush:php;toolbar:false">function isobject(value) {
    return value !== null &amp;&amp; typeof value === 'object' &amp;&amp; !array.isarray(value);
}

console.log(isobject({ a: 1 })); // true
console.log(isobject([1, 2, 3])); // false

17. 合并对象(平面对象)

将两个或多个对象合并为一个。

function mergeobjects(...objs) {
    return object.assign({}, ...objs);
}

console.log(mergeobjects({ a: 1 }, { b: 2 }, { a: 3 })); // { a: 3, b: 2 }

18.深度合并对象

深度合并两个或多个对象。

function deepmerge(...objects) {
    const isobject = (obj) =&gt; obj &amp;&amp; typeof obj === 'object';

    return objects.reduce((prev, obj) =&gt; {
        object.keys(obj).foreach((key) =&gt; {
            const prevval = prev[key];
            const objval = obj[key];

            if (array.isarray(prevval) &amp;&amp; array.isarray(objval)) {
                prev[key] = prevval.concat(...objval);
            } else if (isobject(prevval) &amp;&amp; isobject(objval)) {
                prev[key] = deepmerge(prevval, objval);
            } else {
                prev[key] = objval;
            }
        });
        return prev;
    }, {});
}

const obj1 = { a: 1, b: { x: 10 } };
const obj2 = { b: { y: 20 }, c: 3 };
console.log(deepmerge(obj1, obj2)); // { a: 1, b: { x: 10, y: 20 }, c: 3 }

19. 深度克隆对象

创建对象的深度克隆。

function deepclone(obj) {
    return json.parse(json.stringify(obj));
}

const original = { a: 1, b: { c: 2 } };
const clone = deepclone(original);
clone.b.c = 3;
console.log(original.b.c); // 2
console.log(clone.b.c); // 3

检查在 javascript 中克隆嵌套对象/数组的正确方法以获得更高级的用例。

20.从对象中省略/删除键

返回省略指定键的新对象。

function omitkeys(obj, keys) {
    const result = { ...obj };
    keys.foreach((key) =&gt; delete result[key]);
    return result;
}

console.log(omitkeys({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { b: 2 }

21. 选择关键点来创建新对象

返回仅包含指定键的新对象。

function pickkeys(obj, keys) {
    const result = {};
    keys.foreach((key) =&gt; {
        if (obj.hasownproperty(key)) {
            result[key] = obj[key];
        }
    });
    return result;
}

console.log(pickkeys({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { a: 1, c: 3 }

22. 反转对象键和值

反转对象的键和值。

function invertobject(obj) {
    const result = {};
    object.keys(obj).foreach((key) =&gt; {
        result[obj[key]] = key;
    });
    return result;
}

console.log(invertobject({ a: 1, b: 2, c: 3 })); // { '1': 'a', '2': 'b', '3': 'c' }

23. 检查对象是否为空

检查对象是否为空(没有可枚举属性)。

function isemptyobject(obj) {
    return object.keys(obj).length === 0;
}

console.log(isemptyobject({})); // true
console.log(isemptyobject({ a: 1 })); // false

24. 地图对象

创建一个具有相同键但值由函数转换的新对象。与 array.map() 类似,但针对对象

function mapobject(obj, fn) {
    const result = {};
    object.keys(obj).foreach((key) =&gt; {
        result[key] = fn(obj[key], key);
    });
    return result;
}

console.log(mapobject({ a: 1, b: 2, c: 3 }, (value) =&gt; value * 2)); // { a: 2, b: 4, c: 6 }

25. 过滤对象

创建一个仅包含通过过滤函数的属性的新对象。与 array.filter() 类似,但针对对象

function filterobject(obj, fn) {
    const result = {};
    object.keys(obj).foreach((key) =&gt; {
        if (fn(obj[key], key)) {
            result[key] = obj[key];
        }
    });
    return result;
}

console.log(filterobject({ a: 1, b: 2, c: 3 }, (value) =&gt; value &gt; 1)); // { b: 2, c: 3 }

26. 冻结对象

冻结对象,使其不可变。

function freezeobject(obj) {
    return object.freeze(obj);
}

const obj = { a: 1, b: 2 };
const frozenobj = freezeobject(obj);
frozenobj.a = 3; // will not change the value
console.log(frozenobj.a); // 1

27. 深度冷冻对象

深度冻结一个对象,使其和所有嵌套对象不可变。

function deepfreeze(obj) {
    object.keys(obj).foreach((name) =&gt; {
        const prop = obj[name];
        if (typeof prop == 'object' &amp;&amp; prop !== null) {
            deepfreeze(prop);
        }
    });
    return object.freeze(obj);
}

const obj = { a: 1, b: { c: 2 } };
deepfreeze(obj);
obj.b.c = 3; // will not change the value
console.log(obj.b.c); // 2

javascript 中的常用数组实用程序

28.删除重复项

从数组中删除重复值。

function uniquearray(arr) {
    return [...new set(arr)];
}

console.log(uniquearray([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]

29. 分割数组

将数组分割成指定大小的块。

function chunkarray(arr, size) {
    const result = [];
    for (let i = 0; i 



<h3>
  
  
  30.数组差异
</h3>

<p>返回两个数组之间的差异。<br></p>

<pre class="brush:php;toolbar:false">function arraydifference(arr1, arr2) {
    return arr1.filter((item) =&gt; !arr2.includes(item));
}

console.log(arraydifference([1, 2, 3], [2, 3, 4])); // [1]

javascript 中的常用日期实用程序

这些实用函数可以帮助您在 javascript 中高效地执行各种日期操作和格式化任务。

31. 不使用库格式化日期

将日期格式化为指定的字符串格式。

function formatdate(date, format) {
    const map = {
        mm: ('0' + (date.getmonth() + 1)).slice(-2),
        dd: ('0' + date.getdate()).slice(-2),
        yyyy: date.getfullyear(),
        hh: ('0' + date.gethours()).slice(-2),
        mm: ('0' + date.getminutes()).slice(-2),
        ss: ('0' + date.getseconds()).slice(-2)
    };

    return format.replace(/mm|dd|yyyy|hh|mm|ss/gi, (matched) =&gt; map[matched]);
}

const date = new date();
console.log(formatdate(date, 'dd-mm-yyyy hh:mm:ss')); // example: 28-07-2024 14:30:45

32.添加天数

为日期添加指定的天数。

function adddays(date, days) {
    const result = new date(date);
    result.setdate(result.getdate() + days);
    return result;
}

const date = new date();
console.log(adddays(date, 5)); // adds 5 days to the current date

33.减去天数

从日期中减去指定的天数。

function subtractdays(date, days) {
    const result = new date(date);
    result.setdate(result.getdate() - days);
    return result;
}

const date = new date();
console.log(subtractdays(date, 5)); // subtracts 5 days from the current date

34.计算两个日期之间的天数

计算两个日期之间的天数。

function daysbetween(date1, date2) {
    const oneday = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
    const diffdays = math.round(math.abs((date2 - date1) / oneday));
    return diffdays;
}

const date1 = new date('2024-07-01');
const date2 = new date('2024-07-28');
console.log(daysbetween(date1, date2)); // example: 27 days

35. 检查日期是否是周末

检查给定日期是否是周末。

function isweekend(date) {
    const day = date.getday();
    return day === 0 || day === 6;
}

const date = new date();
console.log(isweekend(date)); // returns true if the date is a weekend, otherwise false

36.计算一个月的天数

获取特定年份的特定月份的天数。

function getdaysinmonth(month, year) {
    return new date(year, month + 1, 0).getdate();
}

const month = 6; // july
const year = 2024;
console.log(getdaysinmonth(month, year)); // example: 31 days in july 2024

37. 2 个日期之间的持续时间

function getDuration(startDate, endDate) {
    const diff = endDate - startDate;
    return Math.floor(diff / (1000 * 60 * 60));
    // 1000 * 60 * 60 for duration in hours
    // 1000 * 60 * 60 * 24 for duration in days
    // 1000 * 60 for duration in minutes
}
const startDate = new Date('2024-07-01T12:00:00');
const endDate = new Date('2024-07-01T15:30:00');
console.log(getDurationInHours(startDate, endDate)); // Duration in hours

对于日期的更高级用例和经过测试的实用程序,请考虑使用日期库,例如 day.js

结论

我们介绍了 37 个有用的 javascript 实用函数,可以帮助您更高效地编码。这些函数简化了数组处理、日期格式化和字符串操作等任务。使用它们可以节省您的时间并减少代码中的错误。

如果本文有帮助,请分享给可能从中受益的其他人。将其添加为书签以供将来参考,如果您有任何未提及的最喜欢的实用功能,请随时在评论中分享。

快乐编码!

卓越飞翔博客
上一篇: 如何开始作为 PgAdmin4 的新开源贡献者
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏