1

What are some clean ways to print out last characters of all words in a string. For example, a phrase like "laugh ride lol hall bozo " --> "hello" and "dog polo boo sudd noob smiley ride " --> goodbye.

These lines would return "1" and undefined. Any help is much appreciated.

var decrypt = function (message) {
    var solution = [];
    for (var i = 0; i < message.length; i++) {
        if(message.charAt(i)===" ") {
            return solution.push(message.charAt(i-1));
        };
    };
};

var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"

var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"
4

4 回答 4

2

Don't return inside the loop, just append the charater to the result. When the loop is done, return what you want. Since you apparently want to return a string, you don't need an array.

var decrypt = function (message) {
    var solution = '';
    for (var i = 0; i < message.length; i++) {
        if(message.charAt(i)===" ") {
            solution += message.charAt(i-1);
        };
    };
    return solution;
};

var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"

var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"

于 2015-01-22T02:03:46.603 回答
1

假设单词用空格分隔,您可以在一行中完成:

var decrypt = function (message) {
  return (message+" ").match(/\w\s/g).join("").replace(/\s/g,"");
}

正则表达式/\w\s/g将匹配一个单词字符后跟一个空格。该.match()方法将返回所有此类匹配的数组。.join()将数组元素连接成一个字符串。然后.replace()将从该字符串中删除空格。

请注意,我正在使用(message+" ")在输入字符串中添加一个额外的空格,以防万一它最后还没有空格。

此外,我展示的代码不允许其中没有任何“单词字符”的字符串。如果要对此进行测试,则需要两行:

var decrypt = function (message) {
  var m = (message+" ").match(/\w\s/g);
  return m ? m.join("").replace(/\s/g,"") : "";
  //include default value for non match here^^
}
于 2015-01-22T02:08:04.757 回答
0

另一个干净的解决方案是

var decrypt = function (message) { 
    return message.split(' ')
        .map(function(word) { return word.slice(-1); })
        .join('');
}

这依赖于 Array.prototype.map,它是在 ES5 中添加的,支持所有现代浏览器(http://kangax.github.io/compat-table/es5/#Array.prototype.map)。

于 2015-01-22T02:43:04.137 回答
0

Considering you only care about the last character of each word, I would loop through the string in reverse. This allows you to also print the last character in the string without appending a space on the end of the encoded message.

function decrypt(message) {
    var c, secret = '', lastSpace = true;
    for (var i = (message || '').length - 1; i >= 0; i--, lastSpace = c === ' ') {
        c = message.charAt(i);
        if (lastSpace) secret = c + secret;
    }
    return secret;
}
于 2015-01-22T03:03:17.293 回答