0

Suppose my string is like:

var str = "USA;UK;AUS;NZ"

Now from some a source I am getting one value like:

country.data = "AUS"

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

var someStr= str.substring(0, str.indexOf(country.data))

In this case I got the same result.

cнŝdk
  • 30,215
  • 7
  • 54
  • 72
David
  • 3,817
  • 8
  • 26
  • 54

5 Answers5

2

You can use split and filter:

var str = "USA;UK;AUS;NZ"
var toBeRemoved = "AUS";
var res = str.split(';').filter(s => s !== toBeRemoved).join(';');
console.log(res);
Faly
  • 12,802
  • 1
  • 18
  • 35
2

Try this :

var result = str.replace(country.data + ';','');

Thanks to comments, this should work more efficently :

var tmp = str.replace(country.data ,''); 
var result = tmp.replace(';;' ,';');
osmanraifgunes
  • 1,410
  • 2
  • 17
  • 42
2

var str = "USA;UK;AUS;NZ"
console.log(str + " <- INPUT");
str = str.split(';');

for (let i = 0; i < str.length; i++) {
  if (str[i] == 'AUS') {
    str.splice(i, 1);
  }
}
console.log(str.join(';') + " <- OUTPUT");
Dhaval Jardosh
  • 6,905
  • 4
  • 25
  • 63
1

Here is a good old split/join method:

var str = "USA;UK;AUS;NZ;AUS";
var str2 = "AUS";
var str3 = str2 + ";";
console.log(str.split(str3).join("").split(str2).join(""));
Commercial Suicide
  • 14,875
  • 14
  • 62
  • 80
1

You can use replace() with a regex containing the searched country, this is how should be the regex /(AUS;?)/.

This is how should be your code:

var str = "USA;UK;AUS;NZ";
var country = "AUS";
var reg = new RegExp("("+country+";?)");
str = str.replace(reg, '');
console.log(str);

This will remove the ; after your country if it exists.

cнŝdk
  • 30,215
  • 7
  • 54
  • 72