从最后一个逗号开始删除字符串中的所有字符

时间:2014-10-20 11:17:42

标签: javascript jquery

说我有一个看起来像这样的字符串:

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

使用jquery,如何删除最后一个逗号之后的所有字符,包括最后一个逗号本身,以便字符串显示为:

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

4 个答案:

答案 0 :(得分:15)

只需阅读直到最后,

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

答案 1 :(得分: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(','))




答案 2 :(得分: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>
&#13;
&#13;
&#13;

答案 3 :(得分: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);
});