最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove all characters from a string from last comma onwards - Stack Overflow

programmeradmin10浏览0评论

Say I have a string that looks like this:

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

Using jquery, how can I remove all the characters after the the last comma including the last comma itself so that the string shows as:

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

Say I have a string that looks like this:

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

Using jquery, how can I remove all the characters after the the last comma including the last comma itself so that the string shows as:

'Welcome, your bed is made' // all characters after last comma are removed
Share Improve this question asked Oct 20, 2014 at 11:17 proPhetproPhet 1,2284 gold badges19 silver badges39 bronze badges 2
  • 1 Yea, you don't need jQuery to do string manipulation. – Cerbrus Commented Oct 20, 2014 at 11:27
  • For some reason my working answer (here) has been downvoted. I'm mentioning this here in case you look at it and think it doesn't work because of the downvote - as the code snippet proves, it works fine. This seems to just be a random downvote for no particular reason related to the answer. – James Donnelly Commented Oct 20, 2014 at 11:34
Add a comment  | 

4 Answers 4

Reset to default 16

Simply read until the last ,:

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

You can using combination of .split() and .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(','))

You can use the string's replace() method with the following regular expression:

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>

Here is your jquery code

<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)

  1. 暂无评论