proPhet
proPhet

Reputation: 1228

Remove all characters from a string from last comma onwards

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

Upvotes: 5

Views: 3560

Answers (4)

Robin
Robin

Reputation: 471

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

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128856

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>

Upvotes: 1

Satpal
Satpal

Reputation: 133453

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(','))

Upvotes: 1

Alex K.
Alex K.

Reputation: 176016

Simply read until the last ,:

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

Upvotes: 16

Related Questions