Greg McMullen Greg McMullen - 5 months ago 22
Javascript Question

JS Regex removes "too much" off of textarea

Working towards submitting a list of ID numbers to the DB. The JS is intended to add/remove the id # from each "tag" and save to the form.

In the example below, the list of

is pulled out of the DB, or was entered in that order by the user. Removing item #1 removes
from the list, as intended, but makes the list 7150 instead of 7,150.

I'm looking for a regex that would help eliminate this type of situation. I've had other issues with other number combinations as well. e.g.
Removing "7" takes out the
of 17. Making the list

"Working" Example. Removing Item 1, takes out both commas.


$("#user-interests").on('click', '.tag', function(e){
var txt = $(this).attr("id");
var group = $(this).data("group");
var regex = new RegExp("(\,)?"+txt+"(\,)?")
var textList = $("#"+group+" textarea");
if ( $(this).hasClass("active") ){
// Remove the class, and from the textarea
console.log("remove from list");
list = textList.text();
list = list.replace(regex, '');
} else {
console.log("Add to list");


<div id="user-interests" class="profile-form active">
<button id="club-descriptions">Show Club Descriptions</button>
<div class="tags" id="club-list">
<textarea name="user[club-list]" class="form-control" id="club-list">7,1,50</textarea>
<div class="show-descriptions">
<button class="tag active" id="1" data-group="club-list">Item 1</button>
<div class="show-descriptions">
<button class="tag " id="7" data-group="club-list">Item 7</button>
<div class="show-descriptions">
<button class="tag " id="150" data-group="club-list">Item 150</button>

Note: I've also thought about using AJAX to submit each item instead of the entire form. Perfectly fine doing it that way if no other alternative is brought to light.

Answer Source

Using the code from @ewwink I was able to define an option that worked for me and cleaned up a lot of the code.

$("#user-interests").on('click', '.tag', function(e){
    var item = $(this).attr('id');
    var group = $(this).data('group');
    var $List = $("#"+group+" textarea");
    var list = ( $List.text() != "" ? $List.text().split(",") : [] );
    var index = list.indexOf(item);
    if ( index === -1 ){
    } else if ( index > -1 ) {
        list.splice(index, 1);

I'm also aware of issues with indexOf() but we're used to encouraging non-IE for some of our other existing products.