用JavaScript字符串中的空值替换空值

时间:2018-02-13 03:07:51

标签: javascript regex

给出以下字符串:

var str = "[,,,1,2,,,3,4,,,,,,5,6]";

我想用空值替换所有“空”值。换句话说,我想要这个结果:

"[null,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6]"

这个几乎有效,但它错过了第一个空值:

var str = "[,,,1,2,,,3,4,,,,,,5,6]";
str.split(',').map(function(x) { return x ? x : 'null' }).join(',')
// Gives [,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6]

同样,我注意到如果我有空值,那么它也错过了最后一个:

var str = "[,,,1,2,,,3,4,,,,,,5,6,,]";
str.split(',').map(function(x) { return x ? x : 'null' }).join(',')
// Gives [,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6,null,]

我有什么想法可以确保第一个和最后一个空值也被替换?

谢谢!

6 个答案:

答案 0 :(得分:1)

这将起作用:



	 var str = "[,,,1,2,,,3,4,,,,,,5,6]";
	 var result = '[' + str.replace(/^\[|\]$/g, '').split(/[,]/).map(function(x) { return x ? x : 'null' }).join(',') + ']';
	 console.log(result);




答案 1 :(得分:1)

秘诀是,当分割时,括号在字符串的开头和结尾处与逗号/数字结合。要解决此问题,您需要在拆分之前删除括号

这可以通过/[\][]/g上的 .replace() 来完成:



var str = "[,,,1,2,,,3,4,,,,,,5,6,]";
console.log(
  str.replace(/[\][]/g, '').split(',').map(function(x) {
    return x ? x : 'null'
  }).join(',')
);




答案 2 :(得分:1)



var str = "[,,,1,2,,,3,4,,,,,,5,6]";
var a = `[${str.slice(1, -1).split(",").map(n => n || "null")}]`
  
console.log(a);




答案 3 :(得分:1)

如上所述 - [和]正在改变你的返回 - 这将删除它们并使用与现有函数相同的函数 - 但是在缩短的字符串上并返回正确的值。



your_turtle.shape(your_image)




答案 4 :(得分:0)

您已删除所有空值。 " ["和"]"并非一无是处。

答案 5 :(得分:0)

String.prototype.repEmptyWithNull = 
function() {return this
  .replace(/,,/g, ',null,')
  .replace(/,,/g, ',null,')
  .replace('[,', '[null,')
  .replace(',]', ',null]')
}

console.log ("[,,,1,2,,,3,4,,,,,,5,6,]".repEmptyWithNull())
console.log ("[,,1,2,,,3,4,,,,,,5,6]".repEmptyWithNull())
console.log ("[,1,2,,,3,4,,,,,,5,6,,]".repEmptyWithNull())
console.log ("[,1,2,,,3,4,,,,,,5,6]".repEmptyWithNull())
console.log ("[1,2,,,3,4,,,,,,5,6,]".repEmptyWithNull())
console.log ("[1,2,,,3,4,,,,,,5,6]".repEmptyWithNull())