0

My Code:

I tried the following code

var str = "Have fun storming the castle!"
var character = "!";

function endsWith(str, character) {
    return str.indexOf(character, str.length - character.length) !== -1;
}

alert(endsWith(str, character));

It is giving the result as True since such word is present in the sentence.

But I need the result as castle! as it is the only word having such character atlast. If multiple words having such character also, I need those words.

4

3 回答 3

2

下面的函数接受字符串和字符,并返回以该字符为最后一个字符的单词数组。它区分大小写,但如果你想让它不区分大小写,那么只需添加.toLowerCase()到比较行。

function getWords(str, character)
{
    var words = str.split(" ");
    var result = [];

    for(var i=0; i<words.length; i++)
    {
        if(words[i].slice(-1) == character)
        {
            result.push(words[i]);
        }
    }

    return result;
}

var str = "Have fun storming the castle!";
var character = "!";

console.log( getWords(str, character) );

输出

[“城堡!”]

多字测试:

console.log( getWords("Have fun storming! the castle!", "!") );

输出

[“风暴!”,“城堡!”]

jsFiddle 演示

于 2012-12-06T09:44:51.037 回答
1
var str = "Have fun storming! the castle!"
var character = "!";

function getWords(str, character)
{
     var words = str.split(" ");
     var result = [];

     for(var i in words)
     {
         //if(words[i].search(character)!="-1")
         if(words[i].substring(words[i].length-1)==character)
         {
             result.push(words[i]);
         }
     }

     return result;
}

alert(getWords(str, character));

如果字符串是“玩得开心冲进城堡!”。然后它返回

城堡!

如果字符串是“玩得开心冲锋!城堡!”。然后它返回

风暴!,城堡!

于 2012-12-06T10:16:11.740 回答
0

您想使用正则表达式。如果您将其定义为“全局”,它将为您提供列表中的所有匹配项:

function endsWith (str, character) {
    regexp = new RegExp ('\\b.*?' + character + '\\b', 'g');
    return str.match (regexp);
}

然而,为了让它真的很好,你应该确保字符被转义,这样它就不会弄乱你的正则表达式:

function escape (character) {
    int num = character.charCodeAt (0);
    String code = '000' + num.toString (16);
    return '\\u' + code.substring (code.length - 4);
}

function endsWith (str, character) {
    regexp = new RegExp ('\\b.*?' + escape (character) + '\\b', 'g');
    return str.match (regexp);
}
于 2012-12-06T09:59:42.453 回答