zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

JS基础测试40期 #51

Open zhangxinxu opened 4 years ago

zhangxinxu commented 4 years ago

关于常见字符格式书写方式的转换实现:

每题2积分。

答题前不要看别人回答,答题后可以,但不能修改自己回答

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式(1积分)。

```js
// 你的JS代码写在这里
 ```

其它:

  1. 首位答题者可获得直播翻牌机会;
  2. 本次答疑直播为11月16日上午10:00,预计20分钟;
liyongleihf2006 commented 4 years ago
function toCamelCase(str){
    return str.replace(/-(.)/g,function($0,$1){
        return $1.toUpperCase()
    })
}    
console.log(toCamelCase("abc-def-ghi"));
function toDashJoin(str){
    return str.replace(/[A-Z]/g,function($0){
        return '-'+$0.toLowerCase()
    })
}
console.log(toDashJoin("abcDefGhi"));
function toCapitalize(str){
    return str.replace(/(\s+|^)(\w)/g,function($0,$1,$2){
        return $1+$2.toUpperCase()
    })
}
console.log(toCapitalize('i like css'));
function toBetterUrl(str){
    return str.replace(/[A-Z]/g,function($0){
        return $0.toLowerCase()
    }).replace(/\s+/g,'-')
}
console.log(toBetterUrl('CSS value type'));
asyncguo commented 4 years ago
//zxx: 3,4测试不通过
const toCamelCase = (letter) => letter.replace(/([-]+)(.)/g, (_, p1, p2, offset) => {
    return offset ? p2.toUpperCase() : p2
})

console.log(toCamelCase('abc-def-ghi'))

const toDashJoin = (letter) => letter.replace(/([A-Z])/g, (_, p1) => {
    return `-${p1.toLowerCase()}`
})

console.log(toDashJoin('abcDefGhi'))

const toCapitalize = (letter) => letter.replace(/([a-zA-Z])/, (_, p1) => {
    return `${p1.toUpperCase()}`
})

console.log(toCapitalize('i Like Css'))

const toBetterUrl = (letter) => letter.replace(/([A-Z\s])(.)/g, (_, p1, p2) => {
    return p1.trim() ? _.toLowerCase() : `-${p2.toLowerCase()}`
})

console.log(toBetterUrl('Css value type'))
Seasonley commented 4 years ago
//zxx: 1,3测试不通过
function toCamelCase(str) {
  let s = str
    .split("-")
    .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
    .join("");
  return s.slice(0, 1).toLowerCase() + s.slice(1);
}

function toDashJoin(str) {
  return str
    .replace(/([a-z\d])([A-Z])/g, "$1-$2")
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1-$2")
    .toLowerCase();
}

function toCapitalize(str) {
  return str.replace(/^\s*[a-z]/, v => v.toUpperCase());
}

function toBetterUrl(str) {
  return toDashJoin(str)
    .replace(/\s+/g, "-")
    .toLowerCase();
}

console.assert(toCamelCase("abc-def-ghi") === "abcDefGhi");
console.assert(toDashJoin("abcDefGhi") === "abc-def-ghi");
console.assert(toCapitalize("i like css") === "I like css");
console.assert(toBetterUrl("CSS value type") === "css-value-type");
XboxYan commented 4 years ago
//zxx: 1,3测试不通过
function toCamelCase(str){
    return str.replace(/\-([a-z])/g,function($1,$2){
        return $2.toUpperCase();
    })
}
function toDashJoin(str){
    return str.replace(/[A-Z]/g,function($1){
        return '-'+$1.toLowerCase();
    })
}
function toCapitalize(str){
    return str.toLowerCase().replace(/\b[a-z]/g,function($1){
        return $1.toUpperCase();
    })
}
function toBetterUrl(str){
    return str.toLowerCase().trim().replace(/\s+/g,"-")
}
toCamelCase("abc-def-ghi");
toDashJoin("abcDefGhi");
toCapitalize("i like css");
toBetterUrl("CSS value type")
NeilChen4698 commented 4 years ago
//zxx: 1,4测试不通过

1.

function toCamelCase(val) {
    return !val ? val : val.replace(/-([a-z])/g, function(str, g) {
        return g.toUpperCase();
    });
}

2.

function toDashJoin(val) {
    return !val ? val : val.replace(/[A-Z]/g, function(str, offset) {
        return (offset === 0 ? '' : '-') + str.toLowerCase();
    });
}

3.

function toCapitalize(val) {
    return !val ? val : val.replace(/(?<=^|\s)[a-z]/g, function(str) {
        return str.toUpperCase();
    });
}

4.

function toBetterUrl(val) {
    return !val ? val : val.toLowerCase().replace(/\s/g, '-');
}
zengqingxiao commented 4 years ago
//zxx: 1,3,4测试不通过

    function toCamelCase(val) {
      let str = val;
      let rep = /-([a-zA-Z]{1})/g
      return str.replace(rep, (map, $1) => {
        return $1.toUpperCase() //将返回值把map替换
      })
    }
    console.log(toCamelCase('abc-dec-caa')) // abcDecCaa

    function toDashJoin(val) {
      let str = val
      let rep = /(?!^)([A-Z]){1}/g;
      return str.replace(rep, (map, $1) => {
        return '-' + $1.toLowerCase()
      }).toLowerCase()
    }
    console.log(toDashJoin('AbcDBecCaa')) // abc-d-bec-caa

    function toCapitalize(val) {
      let str = val
      let rep = /\b([a-zA-Z]){1}/g;
      return str.replace(rep, (map, $1) => {
        return $1.toUpperCase()
      })
    }
    console.log(toCapitalize('i lick zengqinxiao')) // I Lick Zengqinxiao

    function toBetterUrl(val) {
      let str = val
      let rep = /^([a-zA-Z]*)/g
      let rep2 = /(?!^)(?=\b[a-zA-z])/g
      let rep3 = /\s/g
      return str.replace(rep, (map, $1) => {
        return $1.toLowerCase()
      }).replace(rep2, '-').replace(rep3, '')
    }
    console.log(toBetterUrl('CSS value type')) // css-value-type
livetune commented 4 years ago
//zxx: 1,3,4测试不通过,4题目意思弄错了

function toCamelCase(str) {
  return str.replace(/(?:-)([a-z])/g, (s, $1) => {
    return $1.toUpperCase()
  })
}
console.log(toCamelCase('abc-def-ghi'))

function toDashJoin(str) {
  return str.replace(/[A-Z]/g, (s, index) => {
    return (index === 0 ? '' : '-') + s.toLowerCase()
  })
}
console.log(toDashJoin('abcDefGhi'))

function toCapitalize(str) {
  str = str.toLowerCase()
  return str.replace(/^\w|\s\w/g, s => {
    return s.toUpperCase()
  })
}
console.log(toCapitalize('i like css'))

function toBetterUrl(str) {
  str = str.toLowerCase()
  return str.replace(/(\/)([^\/]+)(\/|$)/g, (s, $1, $2, $3) => {
    $2 = $2.trim()
    return $1 + ($2.toLowerCase().replace(/\s+/g, (s1, index) => index === 1 ? '' : '-')) + $3
  })
}
console.log(toBetterUrl('https://www.zhangxinxu.com/wordpress/2019/11/  css value Type'))
ylfeng250 commented 4 years ago
//zxx: 4有误

// 写一个名为toCamelCase的方法,实现把类似'abc-def-ghi'的字符转换成'abcDefGhi'

function toCamelCase(target, delimit = '-',joinFlag='',skipStart=true) {
    return target.split(delimit).map((s, i) => {
        if(skipStart) {
            // 第一个不大写 
            return i === 0 ? s.charAt(0).toLowerCase() + s.slice(1) : s.charAt(0).toUpperCase() + s.slice(1);
        } else {
            // 第一个大写
            return s.charAt(0).toUpperCase() + s.slice(1)
        }

    }).join(joinFlag);
}

console.log(toCamelCase('abc-def-ghi')) //AbcDefGhi

// 写一个名为toDashJoin的方法,实现把驼峰字符串'abcDefGhi'转换成'abc-def-ghi'

function toDashJoin(target, delimit = '-') {
    return target.replace(/[A-Z][a-z]+/g, function (match) {
        return delimit + match.charAt(0).toLowerCase() + match.slice(1)
    })
}

console.log(toDashJoin('abcDefGhi')) // abc-def-ghi

// 写一个名为toCapitalize的方法,实现首字母大写功能,如'i like css'转换成'I Like Css'

function toCapitalize(target,delimit=' ') {
    var joinFlag = delimit;
    return toCamelCase(target, delimit=delimit, joinFlag=joinFlag,skipStart=false);
}

console.log(toCapitalize('i like css'))

// 写一个名为toBetterUrl的方法,实现把类似'CSS value type'转换成'css-value-type'只需考虑空格和大小写处理
function toBetterUrl(target) {
    return target.toLowerCase().replace(/ /g, '-')
}

console.log(toBetterUrl('https://www.zhangxinxu.com/wordpress/2019/11/CSS value type/'))
fzpijl commented 4 years ago
//zxx: 2,3,4测试没通过。题2返回值没有返回
// 1.
function toCamelCase(str) {
    var reg = /-(\w)/g
    return str.replace(reg, function(_, m){
        return m ? m.toUpperCase() : ''
    })
}
// 2.
function toDashJoin(str) {
    var reg = /([A-Z])/g
    str =  str.replace(reg, function(a, m, c, d, e){
        return m ? '-' + m.toLowerCase() : ''
    })
    if(str.startsWith('-')){
        return str.slice(1)
    }
}
// 3.
function toCapitalize(str) {
    var reg = /^(\w)|\b(\w)/g
    return str.replace(reg, function(m){
        return m.toUpperCase()
    })
}
// 4.
function toBetterUrl(str) {
    var reg = /\s/g
    return str.replace(reg, function(m){
        return '-'
    }).toLowerCase()
}
wingmeng commented 4 years ago
//zxx: 1,3测试没过

第 1 题:

function toCamelCase(str) {
  return str.replace(/-([a-z])/g, ($1, $2) => $2.toUpperCase());
}

第 2 题:

function toDashJoin(str) {
  return str.replace(/[A-Z]/g, '-$&').toLowerCase();  // $&:表示匹配到的内容
}

第 3 题:

function toCapitalize(str) {
  return str.split(/\s+/).map(s => s.substr(0, 1).toUpperCase() + s.substr(1)).join(' ');
}

第 4 题:

function toBetterUrl(str) {
  return str.split(/\s+/).map(s => s.toLowerCase()).join('-');
}
Despair-lj commented 4 years ago
//zxx: 1,3测试没通过

// 1. abc-Def-ghi-CSS
function toCamelCase(str) {
  return str.replace(/-([a-z])/gi, function(_, value) {
    return value.toUpperCase();
  });
}
// 2.abcDefGhiCSS
function toDashJoin(str) {
  return str.replace(/([a-z])([A-Z])/g, function(_, low, upp) {
    return low + "-" + upp.toLowerCase();
  });
}
// 3.i like css
function toCapitalize(str) {
  return str.replace(/\b[a-z]/g, function(value) {
    return value.toUpperCase();
  });
}
// 4.   CSS value type  CSS  
function toBetterUrl(str) {
  return str
    .trim()
    .toLowerCase()
    .replace(/\s+(?=[a-z])/g, "-");
}

// 更正
// 1. 破则号后面可能是数字
function toCamelCase(str) {
  return str.replace(/-(\w)/g, function(_, value) {
    return value.toUpperCase();
  });
}
// 3. 要小心 i'm 撇号
function toCapitalize(str) {
  return str.replace(/(^|\s)[a-z]/g, function(value) {
    return value.toUpperCase();
  });
}

console.log(toCamelCase("abc-Def-ghi-CSS"));
console.log(toDashJoin("abcDefGhiCSS"));
console.log(toCapitalize("i like css"));
console.log(toBetterUrl("   CSS value type  CSS  "));
zjgyb commented 4 years ago

哈哈,第一次参加

//zxx: 1,3,4测试没通过
function toCamelCase(str) {
  const reg = /(?:\-)[a-z]/g;
  const newStr = str.replace(reg, (match) => {
    return match.slice(1).toUpperCase();
  });
  return newStr;
}
function toDashJoin(str) {
  const reg = /[A-Z]/g;
  const newStr = str.replace(reg, (match) => {
    return `-${match.toLowerCase()}`;
  });
  return newStr;
}

3.

function toCapitalize(str) {
  // 第一种
  // const reg = /[a-z]+/gi;
  // return str
  //   .match(reg)
  //   .map(ele => ele[0].toUpperCase() + ele.slice(1).toLowerCase())
  //   .join(" ");

  // 第二种
  const reg = /[a-z]+/gi;
  return str.replace(reg, match => {
    const str = match[0].toUpperCase() + match.slice(1);
    return str;
  });
}

4.

function toBetterUrl(str) {
  // 第一种
  // const reg = /[a-z]+/g;
  // return str.match(reg).map(ele => `-${ele.toLowerCase()}`).join('').slice(1);

  // 第二种
  const reg = /[a-z]+/gi;
  const spaceReg = /\s/g;
  return str
    .replace(reg, match => {
      return `${match.toLowerCase()}`;
    })
    .replace(spaceReg, "-");
}
juzhiqiang commented 4 years ago

demo js

// zxx: 方法1拼写有误,扣1分,满分无缘
// 1.
function toCameCase(str){
    if(/^-/.test(str)) return '格式不正确';
    return str.replace(/-(\w)/g,function ($0,$1){
        return $1.toUpperCase();
    });
}
toCameCase('mp-pmn-da');
//不正常示例
toCameCase('-wc-wc-cw'); 

//2.
function toDashJoin(str){
    if(/^[A-Z]/.test(str)) return '错了重来';
    return str.replace(/([A-Z])/g,function ($0){
        return '-'+$0.toLowerCase();
    });
}
toDashJoin('asDsVB');

//3.
function toCapitalize(str){
    return str.replace(/(^[a-z]| +[a-z])/g,function($0){
        return $0.toUpperCase()
    });
}
toCapitalize('i’m like css');

//4.
function toBetterUrl(str){
    return str.toLowerCase().trim().replace(/( +[a-z])/g,function($0,$1){
        return '-'+$0.trim()
    });
}
toBetterUrl('  i’m   Like cSs')
xxf1996 commented 4 years ago
//zxx: 1,4测试不通过
// 2019-11-18:修正代码,测试通过。
// 第一题
function toCamelCase (str) {
  return str.replace(/-([\w])/g, (match, p1) => p1.toUpperCase())
}
// 第二题
function toDashJoin (str) {
  return str.replace(/([A-Z])/g, (match, p1) => '-' + p1.toLowerCase())
}
// 第三题
function toCapitalize (str) {
  return str
    .split(' ')
    .map(word => word.replace(/^([\w])/, (match, p1) => p1.toUpperCase()))
    .join(' ')
}
// 第四题
function toBetterUrl (url) {
  return url.toLowerCase().replace(/[\s]+/g, '-')
}

let case1 = 'abc-def-ghi'
let case2 = 'abcDefGhi'
let case3 = 'i like css'
let case4 = 'https://example.com/11 09/Some Artice'

console.log(toCamelCase(case1))
console.log(toDashJoin(case2))
console.log(toCapitalize(case3))
console.log(toBetterUrl(case4))
guqianfeng commented 4 years ago
//zxx: 题3测试没通过,此题空格无需多个合并成1个
    {
        const toCamelCase = (str) => {
            return str.trim().split("-").map((item, index) => index != 0 ? item[0].toUpperCase() + item.substring(1) : item).join("");
        };

        const toDashJoin = (str) => {
            return str.trim().replace(/[A-Z]/g, function (target) {
                return "-" + target.toLowerCase();
            })
        };

        const toCapitalize = (str) => {
            return str.trim().replace(/\s+/g, " ").split(" ").map(item => item[0].toUpperCase() + item.substring(1)).join(" ");
        };

        const toBetterUrl = (str) => {
            return str.trim().replace(/\s+/g, " ").split(" ").map(item => item.toLowerCase()).join("-");
        };

        let str1 = "abc-def-ghi";
        let str2 = "abcDefGhi";
        let str3 = "i                   like                css";
        let str4 = "CSS value type";
        console.log(toCamelCase(str1));
        console.log(toDashJoin(str2));
        console.log(toCapitalize(str3));
        console.log(toBetterUrl(str4));
    }
les-lee commented 4 years ago
//zxx: 题1名称拼写错误扣1分,题3,4测试未通过
    // 1
    function toCameCase(arg, spliteStr = '-') {
      let regexp = new RegExp(`${spliteStr}(\\w)`, 'g')
      return arg.replace(regexp, (_, c) => c ? c.toUpperCase() : '')
    }
    console.log(toCameCase('abc-df-gg'))

    // 2
    function toDashJoin(arg, spliteStr = '-') {
      return arg.replace(/([A-Z])/g, (_, c) => c ? spliteStr + c.toLowerCase() : '')
    }

    console.log(toDashJoin('abcDefGH'))

    // 3
    function toCapitalize(arg) {
      return arg.replace(/\b([a-z])/g, (_, c) => c ? c.toUpperCase() : '')
    }
    console.log(toCapitalize('i like forntend'))

    // 4
    function toBetterUrl(arg) {
      return arg.replace(/\b([a-z])/g, (_, c) => c ? '-' + c.toLowerCase() : '').replace(/^-/, '').replace(/\s/g, '')
    }
    console.log(toBetterUrl('CSS value type'))
frankyeyq commented 4 years ago
//zxx: 题目4测试未通过

var str1 = 'abc-def-ghi'
str1 = toCamelCase(str1)
console.log(str1)

function toDashJoin(str) {
    return str.replace(/([A-Z])/g, (m, p1) => {
        return '-' + p1.toLowerCase()
    })
}
var str2 = 'abcDefGhi'
str2 = toDashJoin(str2)
console.log(str2)

function toCapitalize(str) {
    return str.split(/\s/).map(s => s.replace(/^[a-z]/, m => m.toUpperCase())).join(' ')
}
var str3 = 'i like css'
str3 = toCapitalize(str3)
console.log(str3)

function toBetterUrl(str) {
    return str.split(/\s/).map(s => s.toLowerCase()).join('-')
}
var str4 = 'CSS value type'
str4 = toBetterUrl(str4)
console.log(str4)
JaimeCheng commented 4 years ago
// 1
function toCamelCase (str) {
  return str.replace(/\-(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
}
// 2
function toDashJoin (str) {
  return str.replace(/([A-Z])/g, "-$1").toLowerCase();
}
// 3
function toCapitalize (str) {
  return (' ' + str).replace(/\ (\w)/g, function (all, letter) {
    return ' ' + letter.toUpperCase();
  }).substr(1);
}
// 4
function toBetterUrl (str) {
  return str.toLowerCase().replace(/\s+/g, "-")
}
console.log(toCamelCase('abc-bcd-dfd'))
console.log(toDashJoin('abcDfgEdf'))
console.log(toCapitalize('i i Like css!'))
console.log(toBetterUrl('CSS  value   type'))
sghweb commented 4 years ago
//zxx: 题3测试未过
// 第一题
function toCamelCase(str) {
  str = str.replace(/\-(\w)/g, function(all, letter) {
    return letter.toUpperCase();
  });
  return str
}
// 第二题
function toDashJoin(str) {
  str = str.replace(/([A-Z])/g, "-$1").toLowerCase();
  return str
}
// 第三题
function toCapitalize(str) {
  str = str.replace(/\b\w+\b/g, function(word) {
    return word.substring(0, 1).toUpperCase() + word.substring(1);
  });
  return str
}
// 第四题
function toBetterUrl(str) {
  str = str.replace(/(\s+)/g, "-").toLowerCase();
  return str
}
rayj1993 commented 4 years ago
// 第一题
function toCamelCase(str) {

    return str.replace(/-./g, function (match) {
        return match.replace('-', '').toUpperCase()
    })

}
console.log(toCamelCase('abc-def-ghi'))
// 第二题
function toDashJoin(str) {

    return str.replace(/[A-Z]/g, function (match) {
        return '-' + match.toLowerCase()
    })

}
console.log(toDashJoin('abcDefGhi'))
// 第三题
function toCapitalize(str) {

    let newString = str.replace(/ ./g, function (match) {
        return match.toUpperCase()
    })
    return newString.charAt(0).toUpperCase() + newString.slice(1)

}
console.log(toCapitalize('i like css'))
// 第四题
function toBetterUrl(str) {

    return str.toLowerCase().replace(/\s+/g, '-')

}
console.log(toBetterUrl('CSS value type'))
ziven27 commented 4 years ago
// 第一题
String.prototype.toCamelCase = function () {
    return this.split('-').map((item, key) => {
        var newItem = item.toLowerCase();
        if (key === 0) {
            return newItem;
        } 
        return newItem.charAt(0).toUpperCase() + newItem.slice(1);
    }).join('');
};
var string1 = "abc-def-ghi";
var newString1 = string1.toCamelCase();
console.log(newString1);

// 第二题
String.prototype.toDashJoin = function () {
    var str = this;
    var len = this.length;
    var strNew = '';
    for (var i = 0; i < len; i++) {
        var char = str.charAt(i);
        var charNum = char.charCodeAt(0);
        if (64 < charNum && charNum < 90) {
            strNew += '-' + char.toLowerCase();
        } else {
            strNew += char;
        }
    }
    return strNew;
};
var string2= 'abcDefGhi';
var newString2 = string2.toDashJoin();
console.log(newString2);

// 第三题
String.prototype.toCapitalize = function () {
    return this.split(' ').map((item) => {
        return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
    }).join(' ');
};
var string3 = 'i like Css';
var newString3 = string3.toCapitalize();
console.log(newString3);

// 第四题
String.prototype.toBetterUrl = function () {
    return this.split('/').map((item) => {
        return item.split(' ').map((it) => {
            return it.toLowerCase();
        }).join('-');
    }).join('/');
};
var string4 = 'https://www.zhangxinxu.com/wordpress/2019/11/css value type/'
var newString4 = string4.toBetterUrl();
console.log(newString4);
// 1,3,4测试不过
// 下面代码方便测试
toCamelCase = function (str) {
    return str.split('-').map((item, key) => {
        var newItem = item.toLowerCase();
        if (key === 0) {
            return newItem;
        } 
        return newItem.charAt(0).toUpperCase() + newItem.slice(1);
    }).join('');
};

// 第二题
toDashJoin = function (str) {
    var len = str.length;
    var strNew = '';
    for (var i = 0; i < len; i++) {
        var char = str.charAt(i);
        var charNum = char.charCodeAt(0);
        if (64 < charNum && charNum < 90) {
            strNew += '-' + char.toLowerCase();
        } else {
            strNew += char;
        }
    }
    return strNew;
};

// 第三题
toCapitalize = function (str) {
    return str.split(' ').map((item) => {
        return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
    }).join(' ');
};

// 第四题
toBetterUrl = function (str) {
    return str.split('/').map((item) => {
        return item.split(' ').map((it) => {
            return it.toLowerCase();
        }).join('-');
    }).join('/');
};

听完课之后修正

第一题

function toCamelCase(str) {
    return str.split('-').map((item, key) => {

        if (key === 0) {
            return item;
        } 
        var newItem = item.toLowerCase();
        return newItem.charAt(0).toUpperCase() + newItem.slice(1);
    }).join('');
};

第二题

function toDashJoin(str) {
    var len = str.length;
    var strNew = '';
    for (var i = 0; i < len; i++) {
        var char = str.charAt(i);
        var charNum = char.charCodeAt(0);
        if (64 < charNum && charNum < 90) {
            strNew += '-' + char.toLowerCase();
        } else {
            strNew += char;
        }
    }
    return strNew;
};

第三题

function toCapitalize(str) {
    return str.split(' ').map((item) => {
        return item.charAt(0).toUpperCase() + item.slice(1);
    }).join(' ');
};

第四题

function toBetterUrl(str) {
    return str.split('/').map((item) => {
        var newItem = [];
        item.split(' ').map((it) => {
            !!it && newItem.push(it.toLowerCase());
            return it;
        });
        return newItem.join('-');
    }).join('/');
};
theDrunkFish commented 4 years ago
// zxx: 题目3名称拼写有误,扣1分

题目1

function toCamelCase (str) {
  var reg = /-\w/g;

  return str.trim().replace(reg, function (matchStr) {
    return matchStr[1].toUpperCase();
  })
}  

题目2

function toDashJoin (str, separate='-') {
  var reg = /(?!=^)[A-Z]/g;

  return str.trim().replace(reg, function (matchStr) {
    return separate + matchStr.toLowerCase();   
  })
}

题目3

function toCapitail (str) {
  var reg = /(?<=\s+|^)[a-z]/g;

  return str.trim().replace(reg, function (matchStr) {
    return matchStr.toUpperCase();
  })
}

题目4

function toBetterUrl (url) {
  var reg = /(?<=[^\s\/])\s+(?=[^\s\/])/g;

  return url.replace(reg, '-').replace(/\s+/g, '').toLowerCase();
}
zy017 commented 4 years ago
//zxx: 1,3测试没过
// 1.
var toCamelCase = function(str) {
  return str.replace(/-([a-z])/g, ($1, $2) => $2.toUpperCase())
}
// 2.
var toDashJoin = function(str) {
  return str.replace(/[A-Z]/g, $1 => '-' + $1.toLowerCase())
}
// 3.
var toCapitalize = function(str) {
  return str.replace(/\b[a-z]/g, $1 => $1.toUpperCase())
}
// 4.
var toBetterUrl = function(str) {
  return str.replace(/\s+/g, '-').toLowerCase()
}

console.log(toCamelCase("abc-def-ghi") === "abcDefGhi")
console.log(toDashJoin("abcDefGhi") === "abc-def-ghi")
console.log(toCapitalize("i like css") === "I Like Css")
console.log(toBetterUrl("CSS value type") === "css-value-type")
whrice commented 4 years ago
//zxx: 1,3,4测试没通过,题1首字母不大写,还有缩进扣1分
        //toCamelCase
        function toCamelCase(str) {
            return str
                .split("-")
                .map(ele => {
                    return ele.slice(0, 1).toUpperCase() + ele.slice(1).toLowerCase();
                })
                .join("");
        }
        console.log(toCamelCase("abc-def-ghi"));
        //toDashJoin
        function toDashJoin(str) {
            return str.replace(/[A-Z]/g, ele => "-" + ele.toLowerCase());
        }
        console.log(toDashJoin("abcDefGhi"));
        //toCapitalize
        function toCapitalize(str) {
            return str.replace(/\b\w+\b/g, ele =>
                ele.replace(ele[0], ele[0].toUpperCase())
            );
        }
        console.log(toCapitalize("i like css"));
        //toBetterUrl
        function toBetterUrl(str) {
            return str.replace(/\s|[A-Z]+\b/g, function (ele) {
                return ele === " " ? "-" : ele.toLowerCase();
            });
        }
        console.log(toBetterUrl("CSS value type"));
silverWolf818 commented 4 years ago

就是split,map,join,问就是不会写正则

//zxx: 3,4测试没过
function toCamelCase(str){
    return str.split("-").map(function(item,index){
        if(index > 0){
            return item.slice(0, 1).toUpperCase() + item.slice(1).toLowerCase();
        }else{
            return item;
        }
    }).join("");
}

function toDashJoin(str){
    return str.replace(/[A-Z]/g,function ($1,$2) {
        return $2 > 0 ? "-" + $1.toLowerCase() : $1;
    })
}

function toCapitalize(str){
    return str.split(" ").map(function (item) {
        return item.slice(0, 1).toUpperCase() + item.slice(1).toLowerCase();
    }).join(" ");
}

function toBetterUrl(str){
    return str.split(" ").map(function (item) {
        return item.toLowerCase();
    }).join("-");
}

console.log(toCamelCase("abc-def-ghi"));
console.log(toDashJoin("abcDefGhi"));
console.log(toCapitalize("i like css"));
console.log(toBetterUrl("CSS value type"));
EmmaYXY commented 4 years ago

//zxx: 1,3,4测试没过

// 1
 function toCamelCase(value) {
  let result = value.replace(/-[a-z]/g, function(match){
      let splited = match.split('-') 
      return splited[1].toUpperCase()
    })
  return result
}
toCamelCase('abc-def-ghi')
// 2
function toDashJoin(value) {
  let result = value.replace(/[A-Z]/g, function(match){ 
      return '-' + match.toLowerCase()
    })
  return result
}
toDashJoin('abcDefGhi')
// 3
function toCapitalize(value) {
  let result = value.replace(/\b[a-z]/g, function(match){
      return match.toUpperCase()
    })
  return result
}
toCapitalize('i like css')
// 4
function toBetterUrl(value) {
  let result = value.replace(/[A-Z]|\s/g, function(match){
      let middle = ''
      if (match === ' ') {
    middle = '-'
     } else {
    middle = match.toLowerCase()
     }
      return middle
    })
  return result
}
toBetterUrl('CSS value type')
GCGligoudan commented 4 years ago

jsbin

//zxx: 题3多空格会运行报错,strArr[i][0] && strArr[i][0].toUpperCase()可修复。题4测试不通过

// 1
function toCamelCase(str) {
  let strArr = str.split('');
  for (let i=0;i<strArr.length;i++) {
    if (strArr[i] === '-') {
      strArr[i + 1] = strArr[i + 1].toUpperCase();
    }
  }
  return strArr.join('').split('-').join('');
}
console.log(toCamelCase('abc-def-ghi'));

// 2
function toDashJoin(str) {
  let strArr = str.split('');
  for(let i=0;i<strArr.length;i++) {
    if (/^[A-Z]+$/.test(strArr[i])) {
      strArr[i] = '-' + strArr[i].toLowerCase();
    }
  }
  return strArr.join('');
}
console.log(toDashJoin('abcDefGhi'));

// 3
function toCapitalize(str) {
  let strArr = str.split(' ');
  for (let i=0;i<strArr.length;i++) {
    strArr[i] = strArr[i][0].toUpperCase() + strArr[i].substring(1);
  }
  return strArr.join(' ');
}
console.log(toCapitalize('i like css'));

// 4
function toBetterUrl(str) {
  let strArr = str.split(' ');
  for(let i=0;i<strArr.length;i++) {
    strArr[i] = strArr[i].toLowerCase();
  }
  return strArr.join('-');
}
console.log(toBetterUrl('CSS value type'));
hangfengnice commented 4 years ago
//zxx: 3,4测试不通过,缩进扣分
  // 第一题:
    function toCamelCase(str) {
      let reg = /\-(\w)/g
      return str.replace(reg, function ($0, $1) {
        return $1.toUpperCase()
      })
    }
    console.log(toCamelCase("hello-world-day-day-up"));

  // 第二题:
    function toDashJoin(str) {
      let reg = /([A-Z])/g
      return str.replace(reg, function($0, $1) {
        return '-' + $1.toLowerCase()
      })
    }
    console.log(toDashJoin("helloWorldDayDayUp"));

   // 第三题:
    function toCapitalize(str) {
      let reg = /\b(\w)/g
      return str.replace(reg, function ($0, $1) {
        return $1.toUpperCase()
      })
    }
    console.log(toCapitalize("hello world day day up"));

   // 第四题
    function toBetterUrl(str) {
      let reg = /\b(\w)/g
      let reg1 = /\s(\w)/g
      return str.replace(reg1, function($0, $1) {
        return "-" + $1.toLowerCase()
      }).replace(reg, function ($0, $1) {
        return $1.toLowerCase()
      })
    }
    console.log(toBetterUrl('Hello world day day up'));
tao1874 commented 4 years ago
//zxx: 3,4测试部通过,还有缩进扣分
 //1.
        function toCamelCase(str) {
            return str.replace(/-\w/g, function ([dash, word]) {
                return word.toUpperCase();
            });
        }
        console.log(toCamelCase("abc-def-ghi"));
        //2.
        function toDashJoin(str) {
            return str.replace(/[A-Z]/g, function (match) {
                return `-${match.toLowerCase()}`;
            });
        }
        console.log(toDashJoin("abcDefGhi"));
        //3.
        function toCapitalize(str) {
            return str.replace(/\b\w/g, function (match) {
                return match.toUpperCase();
            });
        }
        console.log(toCapitalize("i like css"));
        //4.
        function toBetterUrl(str) {
            const toLowerCaseStr = str.replace(/([A-Z])/g, function (match) {
                return match.toLowerCase();
            });
            return toLowerCaseStr.replace(/\s/g, "-");
        }
        console.log(toBetterUrl("CSS value type"));
zhangxinxu commented 4 years ago

本期要点:

  1. 通常字符处理最简洁的方式一定是正则替换,所以学好正则表达式是程序开发人员必须要掌握的。
  2. 测试地址:http://quiz.xiliz.com/qunit40.html 大家可以把自己代码粘贴进去看看结果。
  3. 题3是每个单词首字母大写,it's这种书写s不大写,这一题多空格没必要转换成1个。题4多空格应该转换成一个短横线(.replace(/\s+/g, '-')),不是完整URL处理,而是一个小小的部分。
  4. 题1原来就是驼峰的,不要再处理了。后面是数字的,短横线不用保留。
  5. 通常写业务代码,避免对原型进行方法扩展,浏览器以后可能会原生支持。例如浏览器原生支持toCapitalize方法,但是规则跟你的不一样,于是冲突产生。另外一个原因不方便我测试。
  6. 其他就很基本,不具体展开了。