![](/img/trans.png)
[英]JavaScript: How to remove last word from a string only if the word contains an integer 0-9?
[英]How to remove the last word in a string using JavaScript
如何使用 JavaScript 刪除字符串中的最后一個單詞?
例如,字符串是“我想刪除最后一個單詞”。
使用刪除后,文本框中的字符串將顯示“我要刪除最后一個”
我已經看到如何使用substring函數刪除最后一個字符,但因為最后一個單詞每次都可能不同。 有沒有辦法計算在 JavaScript 中需要刪除多少個單詞?
var str = "I want to remove the last word.";
var lastIndex = str.lastIndexOf(" ");
str = str.substring(0, lastIndex);
獲取最后一個空格,然后獲取子字符串。
一個簡單的方法是使用 JavaScript 的lastIndexOf()和substr()方法:
var myString = "I want to remove the last word";
myString = myString.substring(0, myString.lastIndexOf(" "));
你可以像這樣做一個簡單的正則表達式:
"I want to remove the last word.".replace(/\w+[.!?]?$/, '')
>>> "I want to remove the last"
不過,找到" "
的最后一個索引可能會更快。 這只是更少的代碼。
只是為了好玩而胡鬧,這是一種有趣而令人發指的方式!
"I want to remove the last word.".split(" ").reverse().slice(1).reverse().join(" ")
按照Amir Raminfar 的回答,我找到了這個解決方案。 在我看來,它比接受的答案要好,因為即使您在字符串末尾有空格或使用在最后一個單詞和標點符號之間有空格的語言(如法語),它也能工作。
"Je veux supprimer le dernier mot !".replace(/[\W]*\S+[\W]*$/, '')
"Je veux supprimer le dernier"
正如 OP 隱式要求的那樣,它還刪除了最后一個單詞之前的空格和標點符號。
和平。
使用split
功能
var myString = "I want to remove the last word";
var mySplitResult = myString.split(" ");
var lastWord = mySplitResult[mySplitResult.length-1]
這個問題的最短答案如下,
var str="I want to remove the last word".split(' ');
var lastword=str.pop();
console.log(str.join(' '));
您可以匹配后面沒有單詞字符的空格后面的最后一個單詞。
word=/s+\W*([a-zA-Z']+)\W*$/.exec(string);
if(word) alert(word[1])
如果這里的其他人試圖將字符串名稱拆分為姓氏和名字,請確保處理名稱只有單詞的情況。
let recipientName = _.get(response, 'shipping_address.recipient_name'); let lastWordIndex = recipientName.lastIndexOf(" "); let firstName = (lastWordIndex == -1) ? recipientName : recipientName.substring(0, lastWordIndex); let lastName = (lastWordIndex == -1) ? '' : recipientName.substring(lastWordIndex + 1);
//to get the last word
const animals = "I want to remove the last word.".split(" ");
console.log(animals.slice(-1));
// expected output: word.
//to remove the last word
console.log(animals.slice(0, -1).join(" ");
// expected output: "I want to remove the last"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.