i have the below variable in javascript. i want to remove the starting and ending "comma" sign using jquery/javascript
var test=",1,2,3,4," <---
Expected output: var test="1,2,3,4"
please advice
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.
replace(/,([^,]*)$/, 'and $1'); This will find the last comma in a string and replace it with "and" and anything that came after it.
To remove the last comma of a string in JavaScript, we can use the built-in slice() method by passing the 0, -1 as arguments to it. In the slice() method, negative indexes are used to access the characters from the end of a string.
Regex should help
var edited = test.replace(/^,|,$/g,'');
^,
matches the comma at the start of the string and ,$
matches the comma at the end ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With