简体   繁体   中英

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. 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:

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("-") .

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 . 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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