如何使用JavaScript删除字符串中的最后一个单词 [英] how to remove the last word in the string using JavaScript

查看:116
本文介绍了如何使用JavaScript删除字符串中的最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用JavaScript删除字符串中的最后一个单词?

I would like to know how can I remove the last word in the string using JavaScript?

例如,字符串是我想删除最后一个单词。

For example, the string is "I want to remove the last word."

使用删除后,文本框中的字符串将显示我想删除最后一个

After using removal, the string in the textbox will display "I want to remove the last"

我已经看过如何使用子字符串函数删除最后一个字符,但因为最后一个字每次都可能不同。有没有办法计算在JavaScript中删除需要多少单词?

I've seen how to remove the last character using the substring function, but because the last word can be different every time. Is there a way to count how many word is required to remove in JavaScript?

谢谢

推荐答案

var str = "I want to remove the last word.";
var lastIndex = str.lastIndexOf(" ");

str = str.substring(0, lastIndex);

获取最后一个空格,然后获取子字符串。

Get last space and then get sub string.

这篇关于如何使用JavaScript删除字符串中的最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆