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
  • 31,391
  • 7
  • 56
  • 78
David
  • 4,266
  • 8
  • 34
  • 69

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
  • 13,291
  • 2
  • 19
  • 37
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,438
  • 2
  • 17
  • 43
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
  • 7,151
  • 5
  • 27
  • 69
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(""));
P.S.
  • 15,970
  • 14
  • 62
  • 86
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
  • 31,391
  • 7
  • 56
  • 78