John Smith
John Smith

Reputation: 1687

Trimming the comma at the start of the string

I need your help.

I have the following function below that converts select box contents and turns them into one long string.

The problem is that there is a comma at the start once the function has been ran.

How can the existing function be modified so that I can trim/drop the comma at the start of the string

initial result: ,A,B,C,D,E,F

expected end result: A,B,C,D,E,F

function select2var(select) {

    var x = document.getElementById(select).options

    var values = []

    for (var i=0; i < x.length; i++) {
        values.push(x[i].value);
    }
    return values.join(",");
}

function test() {

document.getElementById('box').value = select2var('alphabet')

}

HTML markup:

<select id="alphabet">
    <option value=""></option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
    <option value="E">E</option>
    <option value="F">F</option>
</select>

Upvotes: 1

Views: 88

Answers (2)

You can either not add the empty value, or -if you have multiple empty values- you can use filter:

// values = ['','A','B','','','C',...]

values = values.filter( function(v) {
  // return 'false' when v is a false-coercing value, like the empty string
  return !!v;
});

// values = ['A','B','C',...]

Or the shorter version (exploiting the built-in Boolean function)

values = values.filter( Boolean );

Upvotes: 0

Alex K.
Alex K.

Reputation: 175826

Don't add empty values:

if (x[i].value.length) {
   values.push(x[i].value)
}

Upvotes: 8

Related Questions