Codewars|Break camelCase

262 阅读1分钟

DESCRIPTION:

Complete the solution so that the function will break up camel casing, using a space between words.

Example

"camelCasing"  =>  "camel Casing"
"identifier"   =>  "identifier"
""             =>  ""

思路:

一开始的思路是用 CharCodeAt() 判断,大写字母是从65到90。找到这个index之后加一个空格就可以。

后来看到其他人的解法,发现正则也可以。

Solution:

我的解法

function solution(string) {
    return string.split('').map(i=>(
      (i.charCodeAt(0) >= 65 && i.charCodeAt(0) <= 90) ? ' ' + i : i
    )).join('')
}

正则:

function solution(string) {
  return(string.replace(/([A-Z])/g, ' $1'));
}