简体   繁体   English

使用正则表达式替换所有逗号和方括号

[英]Replace all commas and square brackets using Regex Expression

Hope u people will be fine. 希望你们会好起来的。 I want to print a array variable in javascript, but the problem is that when i print the array a comma seperated list is shown. 我想在javascript中打印数组变量,但是问题是当我打印数组时,显示了逗号分隔列表。 But i do not want commas between each array value. 但是我不希望每个数组值之间出现逗号。 Is there any method to print array variable wihtout commas? 有没有什么方法来打印带有逗号的数组变量?

If not, Please tell me what is the regex expression to replace all occurence of '],['(wihtout quotes) with ']['. 如果不是,请告诉我用'] ['替换所有出现的'],['(不带引号)'的正则表达式是什么。

Waiting for ur kind replies. 等待您的回复。

Regards 问候

You can use regex, but the most obvious way is to just join the array, IMO: 您可以使用正则表达式,但最明显的方法是仅join数组IMO:

var arr = ["a", "b", "c", "d"];
alert(arr.join("")); // alerts "abcd"

Note that join is flexible in that you could change the delimiter above with something like arr.join("-") . 请注意, join是灵活的,因为您可以使用arr.join("-")类的arr.join("-")来更改上面的分隔符。

If you are seeing '],[' then you may have arrays as content of the array (ie a multi-dimentional array) and have tried Array.prototype.join . 如果看到'],[',那么您可能将数组作为数组的内容(即多维数组),并尝试了Array.prototype.join eg 例如

var x = [[1,2],[3,4]];
alert(x);  // 1,2,3,4
alert(x.join(''));  // 1,23,4

Simply using the Array's built-in toString method with an regular expression may do the job: 只需将Array的内置toString方法与正则表达式配合使用即可完成此工作:

var re = /,/g;
alert(x.toString().replace(re, ''));  // 1234

However a better method (ie applicable to a wider variety of cases) might be to iterate over the contents of the array and deal with values that are also arrays. 但是,更好的方法(即适用于多种情况)可能是遍历数组的内容并处理也是数组的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM