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.

0

5 Answers 5

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");

Sign up to request clarification or add additional context in comments.

Comments

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);

3 Comments

In this case I left with two ;;
I've updated, take a look
Thanks I am checking
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(';;' ,';');

4 Comments

This results in 'USA;UK;;NZ', leaving an orphaned delimiter. Yes, AUS is gone, but it's doubtful this is the desired output.
I edited. try now.
you've still the case of the final value. Say you wanted to remove NZ... this would fail.
var result = str.replace(country.data ,''); var result2 = result .replace(';;' ,';'); This hould work. @ᴄʜaᴢsᴏʟᴏ
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.

Comments

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(""));

4 Comments

In this case I left with two ;;
@David, yes, but it's easy to solve, just add + ";" to your second string. I have updated the answer.
this fails if you want to remove the final value
@ᴄʜaᴢsᴏʟᴏ, updated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.