admin管理员组

文章数量:1425214

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 bees 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 ma doens't exist.

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

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 bees 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 ma doens't exist.

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

Share Improve this question edited Aug 9, 2017 at 11:27 Red asked Aug 9, 2017 at 10:24 RedRed 7,36410 gold badges53 silver badges95 bronze badges 5
  • can string2 be first or last? Or is it always in the middle? – baklazan Commented Aug 9, 2017 at 10:26
  • It can be anywere. – Red Commented Aug 9, 2017 at 10:28
  • @Red Your string may have duplicates ? – Suresh Atta Commented Aug 9, 2017 at 10:29
  • 4 string.split(',').filter(s => s !== 'string2').join(','); – Phylogenesis Commented Aug 9, 2017 at 10:30
  • No, they are unique – Red Commented Aug 9, 2017 at 10:30
Add a ment  | 

8 Answers 8

Reset to default 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.

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

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

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

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

Or :

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

You can check for the ma 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,''); }

You should replace only 1 ma 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);

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

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

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 ma by adding or subtracting 1.

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.

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

So I'm assuming that string contains spaces also.

So question is - how can we detect the ma 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>

本文标签: JavaScript replace string and comma if comma exists else only the stringStack Overflow