Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove substring and comma if exist on left or right side

I have the following string:

"house,car,table"

I need to properly handle the comma removal, so much so that If I remove "car" the output should be:

"house,table"

If I remove "table" the output should be:

"house,car"

like image 202
user1916077 Avatar asked Dec 06 '25 17:12

user1916077


2 Answers

You can use the .split() in an array then .filter() out the target text after words .join() to create a string.

var str = "house,car,table";
str = str.split(',').filter(x => x !== 'car').join(',');

console.log(str)
like image 61
Satpal Avatar answered Dec 09 '25 16:12

Satpal


You can use string#split, string#indexOf array#splice and arr#join

var str = "house,car,table";
var arr = str.split(',');

var index = arr.indexOf('car');
arr.splice(index, 1);

console.log(arr.join(','));
like image 40
Pankaj Shukla Avatar answered Dec 09 '25 17:12

Pankaj Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!