2

I got a string like:

var string = "string1,string2,string3,string4";

I got to replace a given value from the string. So the string for example becomes like this:

var replaced = "string1,string3,string4"; // `string2,` is replaced from the string

Ive tried to do it like this:

var valueToReplace = "string2";
var replace = string.replace(',' + string2 + ',', ''); 

But then the output is:

string1string3,string4

Or if i have to replace string4 then the replace function doesn't replace anything, because the comma doens't exist.

How can i replace the value and the commas if the comma(s) exists? If the comma doesn't exists, then only replace the string.

5
  • can string2 be first or last? Or is it always in the middle? Commented Aug 9, 2017 at 10:26
  • It can be anywere. Commented Aug 9, 2017 at 10:28
  • @Red Your string may have duplicates ? Commented Aug 9, 2017 at 10:29
  • 4
    string.split(',').filter(s => s !== 'string2').join(','); Commented Aug 9, 2017 at 10:30
  • No, they are unique Commented Aug 9, 2017 at 10:30

8 Answers 8

3

Modern browsers

var result = string.split(',').filter( s => s !== 'string2').join(',');

For older browsers

var result = string.split(',').filter( function(s){ return s !== 'string2'}).join(',');

First you split string into array such as ['string1', 'string2', 'string3', 'string4' ]

Then you filter out unwanted item with filter. So you are left with ['string1', 'string3', 'string4' ]

join(',') convertes your array into string using , separator.

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

9 Comments

I know I wrote exactly this as a comment, but to be a good answer, it should really include an explanation of how it works.
It works, one more question. Whats the oldschool JavaScript version of this one? In IE this doens't work..
Which version of IE is the minimum acceptable version for you?
@Phylogenesis 9
Then something like string.split(',').filter(function (s) { return s !== 'string2'; }).join(','); should work?
|
2

Split the string by comma. You get all Strings as an array and remove the item you want. Join back them by comma.

var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var parts = string.split(",");
parts.splice(parts.indexOf(valueToReplace), 1);
var result = parts.join(",");
console.log(result);

Comments

1

You only need to replace one of the two commas not both, so :

var replace = string.replace(string2 + ',', ''); 

Or :

var replace = string.replace(',' + string2, ''); 

You can check for the comma by :

if (string.indexOf(',' + string2)>-1) {
    var replace = string.replace(',' + string2, '');
else if (string.indexOf(string2 + ',', '')>-1) {
    var replace = string.replace(string2 + ',', '');
} else { var replace = string.replace(string2,''); }

2 Comments

Yes, but what if ive to replace string4? then the comma doens't exist at the end and the replace doenst replace anything.
You can check as mentioned above.
0

You should replace only 1 comma and also pass the correct variable to replace method such as

var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var replaced = string.replace(valueToReplace + ',', ''); 
alert(replaced);

Comments

0

You can replace the string and check after that for the comma

var replace = string.replace(string2, ''); 
if(replace[replace.length - 1] === ',')
{
    replace = replace.slice(0, -1);
}

Comments

0

You can use string function replace();

eg:

var string = "string1,string2,string3,string4";
var valueToReplace = ",string2";
var replaced = string.replace(valueToReplace,''); 

or if you wish to divide it in substring you can use substr() function;

var string = "string1,string2,string3,string4";
firstComma = string.indexOf(',')
var replaced = string.substr(0,string.indexOf(','));
secondComma = string.indexOf(',', firstComma + 1)
replaced += string.substr(secondComma , string.length);

you can adjust length as per your choice of comma by adding or subtracting 1.

Comments

0
str = "string1,string2,string3"
tmp = []
match = "string3"
str.split(',').forEach(e=>{
    if(e != match)
        tmp.push(e)
})
console.log(tmp.join(','))

okay i got you. here you go.

1 Comment

What if its last item?
0

Your question is - How can i replace the value and the commas if the comma(s) exists?

So I'm assuming that string contains spaces also.

So question is - how can we detect the comma existence in string?

Simple, use below Javascript condition -

var string = "string1 string2, string3, string4";
var stringToReplace = "string2";
var result;

if (string.search(stringToReplace + "[\,]") === -1) {
  result = string.replace(stringToReplace,'');
} else {
  result = string.replace(stringToReplace + ',','');
}

document.getElementById("result").innerHTML = result;
<p id="result"></p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.