说我有一个看起来像这样的字符串:
'Welcome, your bed is made, your tea is ready.'
使用jquery,如何删除最后一个逗号之后的所有字符,包括最后一个逗号本身,以便字符串显示为:
'Welcome, your bed is made' // all characters after last comma are removed
答案 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;
答案 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);
});