2014-10-20 152 views
4

說我有一個字符串,它看起來像這樣:從最後一個逗號字符串中刪除所有字符起

'Welcome, your bed is made, your tea is ready.' 

使用jQuery,我怎麼可以刪除所有字符的最後一個逗號,包括最後一個逗號本身後因此該字符串顯示爲:

'Welcome, your bed is made' // all characters after last comma are removed 
+1

是的,你不需要jQuery來做字符串操作。 – Cerbrus 2014-10-20 11:27:06

+0

出於某種原因,我的工作答案([這裏](http://stackoverflow.com/a/26464445/1317805))已被低估。我在這裏提到這一點,以防你看到它,並認爲它不起作用,因爲downvote - 如代碼片段證明的,它工作正常。這似乎只是一個隨機downvote沒有特別的原因相關的答案。 – 2014-10-20 11:34:18

回答

15

只需閱讀,直到最後,

str = str.substr(0, str.lastIndexOf(",")); 
1

可以使用的.split()組合.slice()

var str = 'Welcome, your bed is made, your tea is ready.'; 
 
var arr = str.split(','); 
 
arr = arr.splice(0, arr.length - 1) 
 
alert(arr.join(','))

1

您可以使用字符串的replace()方法具有以下的正則表達式:

var str = 'Welcome, your bed is made, your tea is ready.' 
 

 
str = str.replace(/,([^,]*)$/, ''); 
 

 
$('#result').text(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<p id="result"></p>

+0

小心解釋downvote?如果你運行的代碼片段,這完美的作品... – 2014-10-20 11:29:10

+0

基本上,這:http://jsperf.com/regex-vs-lastindexof-1 不要使用正則表達式進行簡單的字符串操作。 – Cerbrus 2014-10-20 11:38:34

+1

@Cerbrus除非你以60fps運行遊戲,否則這裏的差異可以忽略不計。 – 2014-10-20 11:53:44

0

這裏是你的jQuery代碼

<script type="text/javascript"> 
$(document).ready(function(){ 
    var str = 'Welcome, your bed is made, your tea is ready.'; 
    var n = str.lastIndexOf(","); 
    var str1 = str.slice(0,n); 
}); 
+0

str1有最終的字符串。 – Robin 2014-10-20 11:40:07

相關問題