简体   繁体   中英

replace the presence of certain characters in a string in javascript or angularjs

I have a string named pageList= [[],[2567,2568,],[2569,2570,2571,2537,],[2538,2586,2587,2588,],[2589,2590,2591,2592,2593,]] I need to remove the presnce of [], with (empty) and ,[] with (empty) and ,] with ] . I tried the code

              pageList = pageList.replace(/,]/g,']');                 
              pageList = pageList.replace(/[]/g,''); 
              pageList = pageList.replace(/[/]/g,'');

But its is replacing the ,] with ] but removing the ,[] and [], is not working.The output I am getting now is [[],[2567,2568],[2569,2570,2571,2537],[2538,2586,2587,2588],[2589,2590,2591,2592,2593]]

You do not need regex here as it is not a string.

This being an array so extra , will automatically be removed. To remove [] you can use .filter() here

 var pageList= [[],[2567,2568,],[2569,2570,2571,2537,],[2538,2586,2587,2588,],[2589,2590,2591,2592,2593,]]; pageList = pageList.filter(el => el.length!==0) console.log(pageList); 

PS: If your data is in string format then you might need to parse it to array by doing JSON.parse(pageList);

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