前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaScript 字符串练习题之实现

JavaScript 字符串练习题之实现

作者头像
前端GoGoGo
发布2018-08-24 17:21:15
9060
发布2018-08-24 17:21:15
举报

JavaScript 字符串练习题见这里

** 题 1:首字母改大写 **

代码语言:javascript
复制
function firstLetterToUpperCase(str) {
    var res;
    if (typeof str === 'string') {
        res = str.charAt(0).toUpperCase() + str.substr(1);
    } else {
        res = str;
    }
    return res;
}

** 题 2:去字符串头尾空格 **

代码语言:javascript
复制
function trim(str) {
    var res;
    if (typeof str === 'string') {
        res = str.replace(/^\s+/g, '')
            .replace(/\s+$/g, '');
    } else {
        res = str;
    }
    return res;
}

** 题 3:将字符串中 _ 后面的小写字母变大写,并且删除 _ **

代码语言:javascript
复制
function toCamelStyle(str) {
    var res;
    if (typeof str === 'string') {
        var isFisrstLetterUnderscore = str.charAt(0) === '_';
        var wordArr;
        if(isFisrstLetterUnderscore){
            str = str.substr(1);
        }
        wordArr = str.split('_');
        wordArr = wordArr.map(function (word, index) {
            // firstLetterToUpperCase 在题目 1 中实现
            return index === 0 ? word : firstLetterToUpperCase(word);
        });
        res = wordArr.join('');
        if(isFisrstLetterUnderscore){
            res = '_' + res;
        }
    } else {
        res = str;
    }
    return res;
}

** 题 4:删除字符串中所有的数字 **

代码语言:javascript
复制
function removeNum(str) {
    var res;
    if (typeof str === 'string') {
        res = str.replace(/\d/g, '');
    } else {
        res = str;
    }
    return res;
}

** 题 5: 反转字符串 **

代码语言:javascript
复制
function reverse(str) {
    var res;
    if (typeof str === 'string') {
        res = [];
        var charArr = str.split('');
        var currIndex = charArr.length - 1;
        for(; currIndex >= 0; currIndex--){
            res.push(charArr[currIndex]);
        }
        res = res.join('');
    } else {
        res = str;
    }
    return res;
}

** 题 6: 统计字符串中各字符在字符串中出现的数量 **

代码语言:javascript
复制
function caculateExistNum(str) {
    var res = false;
    if (typeof str === 'string') {
        res = {};
        var charArr = str.split('');
        charArr.forEach(function (eachChar) {
            res[eachChar] = res[eachChar] ? res[eachChar] + 1 : 1;
        });
    }
    return res;
}

本文遵守创作共享CC BY-NC-SA 4.0协议

网络平台如需转载必须与本人联系确认。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015.12.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档