RemoveLastWord Javascript function



我试图删除给定字符串的最后一个单词,但它不起作用,我不知道为什么有人能帮我请

功能图片删除最后一个单词和错误。

第二次尝试功能删除最后一个单词和不同错误

第一张和第二张图片的区别在于我使用了

的lastIndexOf中没有空间

text.lastIndexOf('');

在第二次尝试中,我使用了

的lastIndexOf中的空间

text.lastIndexOf(' ');

我无法使它工作。

有人能帮帮我吗?

我的程序代码。

function removeLastWord(text) {
newtext = text.substring(0, text.lastIndexOf(' '));
return newtext;
}

错误在图片中

获取字符串,用空格将其拆分为单词数组,然后从该数组中截取最后一个条目(最后一个单词(,并用空格将它们连接起来。

这是代码:

words = "Lorem ipsum dolor sit amet anim id est laborum.";
exceptLast = words.split(" ").slice(0, -1).join(" ");

结果是:

Lorem ipsum dolor sit amet anim id est

除了最后一句话。将它制作成一个函数并用极值(单个单词、空字符串(进行测试也很好:

function removeLastWord(input) {
if ( (typeof input === 'string') && input.length > 0) {
if (input.split(" ").length == 1) {
// Single word input, just return it as it is
return input
} else {
// Multiple words in the string, remove the last word
return  input.split(" ").slice(0, -1).join(" ");
}
} else {
// Invalid input, just return ''
return '';
}
}
removeLastWord("Lorem ipsum dolor sit amet anim id est laborum.");
removeLastWord("Lorem");
removeLastWord("");
removeLastWord('');
removeLastWord('A');
removeLastWord('Hallo');

当文本中只有一个单词时,你不想从注释中的描述中删除最后一个单词,所以你可以有条件,这样当你在代码中描述它时,你可以做你想做的一切。

您可以使用此

function removeLast(str){
return str.substr(0, str.lastIndexOf(" "))
}

这是一种使用正则表达式的方法

function removeLastWord(text) {
return text.replace(/(s+([^s]|n|r)+)$/g, "");
}

最新更新