Remove all characters from the last comma string

Let's say I have a line that looks like this:

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

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

'Welcome, your bed is made' // all characters after last comma are removed
+4
source share
4 answers

Just read to the last ,:

str = str.substr(0, str.lastIndexOf(","));
+15
source

You can use a 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(','))
Run codeHide result
+1
source

You can use the string method replace()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>
Run codeHide result
+1
source

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
source

All Articles