Codewars-Javascript训练手册:字符串(上)

Recursive reverse string(递归反转字符串)

Description:
Your objective is to complete a recursive function reverse() that receives str as String and returns the same string in reverse order

Rules:

  • reverse function should be executed only N times. N = length of the input string
  • helper functions are not allowed
  • changing the signature of the function is not allowed

stackoverflow解决方案:

function reverse (str) {
    if (str === "") {
        return "";
    } else {
        return reverse(str.substr(1)) + str.charAt(0);
    }

}

可改写为:return str=="" ? "":reverse(str.substr(1)) + str.charAt(0),substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。语法:

stringObject.substr(start,length)

ECMAscript 没有对该方法进行标准化,因此反对使用它。 slice() 可以代替substr().charAt() 方法可返回指定位置的字符,注释:字符串中第一个字符的下标是 0。如果参数 index 不在 0 与 string.length 之间,该方法将返回一个空字符串。可以使用str[0]方法代理

Codewars解决方案:

function reverse(str) {
  return str.length == 1 ? str : reverse(str.substr(1)) + str[0];
}

slice() 方法可提取字符串的某个部分,并以新的字符串返回被提取的部分。语法:

stringObject.slice(start,end)

字符串去重

Description:
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

Solution:

var uniqueInOrder=function(iterable){
  var t = [],
  tt='';
  for(var i=0,len=iterable.length;i<len;i++){

if(tt!==iterable[i]){t.push(iterable[i])};
 tt=iterable[i];
  }
return t;
}

Dubstep

Description:
a song with words “I AM X” can transform into a dubstep remix as “WUBWUBIWUBAMWUBWUBX” and cannot transform into “WUBWUBIAMWUBX”.
Output
Return the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space.

Solution:

function songDecoder(song){
var rs = [];//使用数组进行push操作
for(var i=0,len=song.length;i<len;){
if(len>=3+i && song.substr(i,3)=="WUB"){
if(rs[rs.length-1]!=" ")//去除多个“WUB”造成的空格
  rs.push(" ");//替换“WUB”为空格
  i+=3;
}else{
  rs.push(song[i]);
  i++;
}
}
var str = rs.join('');//返回一个字符串
return str.replace(/(^s*)|(s*$)/g, "");//使用正则表达式来去除首尾的空格
}

Codewars上的解决方案:

//方案一
function songDecoder(song){
  return song.replace(/(WUB)+/g," ").trim()
}
//方案二
function songDecoder(song){
  return song.split("WUB").filter(function(v){return v!==""}).join(" ");
}
原文地址:https://www.cnblogs.com/xihe/p/6138622.html