Jquery How to remove an item with or without a comma?

Given an input that may contain values ​​such as:

<input type="hidden" value="XXXXXXX" />

<input type="hidden" value="XXXXXXX, YYYYYYYY" />

<input type="hidden" value="XXXXXXX, YYYYYYYY, ZZZZZZZZZZ" />

I want to use jQuery to delete: XXXXXXX, but if XXXXXXX has a comma after (XXXXXXX,), I need the comma to be removed.

This is what I have now:

uuid = XXXXXXX
.val(attachedUUIDs.replace(uuid + ',', '' ));
.val(attachedUUIDs.replace(uuid, '' ));                                 

Ideas to make it clean? Thanks

+3
source share
3 answers

This should do:

var uuid = 'XXXXXXX';
$('input').val(function (index, value) {
    return value.replace(new RegExp('\s*'+uuid+',?\s*', 'g'), '');
});
+2
source

Separate the value in the array using the separator ",", and then add the second element of the array as the value! Could this help you?

+2
source

?.

$('input:hidden').val(attachedUUIDs.replace(/XXXXXXX,?/, '' ));
+1

Source: https://habr.com/ru/post/1778435/


All Articles