18

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

1

5 Answers 5

44

Regex should help

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

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

Sign up to request clarification or add additional context in comments.

7 Comments

how to remove | instead of ,?
@ThulasiRam, replace , with \| so it ends being test.replace(/^\||\|$/g,'')
how would I remove the comma that's followed by a space?
This is the only truly correct answer, the others will remove any character from the beginning and end of your string, regardless of whether they are a comma or not
@anees just add + after the commas. .replace(/^,+|,+$/g,'')
|
3

Below code sample will do this

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

Comments

2

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

Comments

2

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)

Comments

-1

Even easier

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

1 Comment

It will remove strings which do not match the "," as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.