Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 892
proPhet Avatar asked Oct 20 '14 11:10

proPhet


People also ask

How do you remove trailing commas from a string?

To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second. The method will return a copy of the string without the leading or trailing comma. Copied!

How do you split a string at the last comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

How do you remove the last comma in output?

For removing the last comma from a string, you can use the slice() method, replace() method, or substring() method. The slice() and the substring() methods extract the strings except for the last comma, while the replace() method only replaces the last comma in a string with an empty string.

How do I remove the last comma in Python?

Use the str. rstrip() method to remove the last comma from a string, e.g. new_str = my_str. rstrip(',') .


1 Answers

Simply read until the last ,:

str = str.substr(0, str.lastIndexOf(","));
like image 67
Alex K. Avatar answered Nov 08 '22 21:11

Alex K.