清理逗号&更换后的空格

时间:2018-05-28 10:02:25

标签: javascript

假设字符串中有三个水果名称,可以按任何顺序排列。例如

var frt = "banana, apple, orange";
var frt = "apple, banana, orange";
var frt = "banana, orange, apple";

现在,我使用以下方法删除一个(随机)水果:

var frt_rem = "apple";
frt = frt.replace(frt_rem, "");

这将保留原始字符串,如下所示:

var frt = "banana, apple, orange"; // banana, , orange
var frt = "apple, banana, orange"; // , banana, orange
var frt = "banana, orange, apple"; // banana, orange, 

逗号和空格不可预测地留在字符串中。有没有一种清理字符串的好方法?

4 个答案:

答案 0 :(得分:0)

您可以创建一个可重复使用的函数,该函数将使用逗号分割字符串,然后从数组中删除该水果。之后,使用逗号和空格连接数组元素,如下所示:

function removeFruits(str, removeWord){
  var strArray = str.split(',').map(x=>x.trim());
  strArray.splice(strArray.indexOf(removeWord), 1);
  var res = strArray.join(', ');
  return res;
}
var frt = "banana, apple, orange";
var frt_rem = "apple";
var res = removeFruits(frt, frt_rem);
console.log(res);
frt = "apple, banana, orange";
res = removeFruits(frt, frt_rem);
console.log(res);
frt = "banana, orange, apple";
res = removeFruits(frt, frt_rem);
console.log(res);

答案 1 :(得分:0)

在替换添加逗号之前替换函数就像...

var frt_rem = "apple";
frt = frt.replace(", " + frt_rem, "");

答案 2 :(得分:0)

将字符串拆分为数组,便于清理和替换元素。

var frt_rem = "apple";

function replaceArray(frt) {
  var splitArray = frt.replace(/ /g, "").split(",");
  var index = splitArray.indexOf("apple");
  if (index > -1) {
    splitArray.splice(index, 1);
  }
  return splitArray.join(", ");
}

var frt = "banana, apple, orange";
console.log(replaceArray(frt)); //banana, orange

frt = "apple, banana, orange";
console.log(replaceArray(frt)); //banana, orange

frt = "banana, orange, apple";
console.log(replaceArray(frt)); //banana, orange

答案 3 :(得分:0)

您可以使用此

frt.replace("apple","").replace(/\s/g, '').split(",").filter(String).join(",")