Amit
Amit

Reputation: 7035

remove starting and ending comma from variable in javascript

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

Upvotes: 18

Views: 42087

Answers (5)

Renish Gotecha
Renish Gotecha

Reputation: 2522

In my case, I am having multiple comma in between the numbers as well.

const str = ",1,8487,8,,848780,888,,";
const parsedStr = str.match(/\d+/g)
document.write(parsedStr)

Upvotes: 1

barcrab
barcrab

Reputation: 199

Even easier

var result = test.slice(1,-1);

Upvotes: -1

Ankit
Ankit

Reputation: 2753

Below code sample will do this

        var str = ",1,2,3,4,5,6,7,8,9,";
        str = str.substring(1,str.lastIndexOf(","));

Upvotes: 3

Josh Leitzel
Josh Leitzel

Reputation: 15199

test.substring(1, test.length - 1); should do it for you.

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Regex should help

var edited = test.replace(/^,|,$/g,'');

^, matches the comma at the start of the string and ,$ matches the comma at the end ..

Upvotes: 44

Related Questions