简体   繁体   English

用大括号分割字符串成为参数

[英]Split string with brace to become parameter

If I have a input value "a[123],b[456],c[789]" and I want to return as "a=123&b=456&c789" 如果我有一个输入值“ a [123],b [456],c [789]”并且我想返回为“ a = 123&b = 456&c789”

I've tried below code but no luck.. Is there a correct way to implement this? 我试过下面的代码,但是没有运气。是否有实现此目的的正确方法?

 var str = "a[123],b[456],c[789]" var string = (str).split(/\\[|,|\\]/); alert(string); 

One option is: 一种选择是:

var rep = { '[': '=', ']': '', ',': '&' };
var query = str.replace(/[[,\]]/g, el => rep[el] );

The delimiters are already there, it's just a matter of replacing one delimiter with another. 分隔符已经存在,只需将一个分隔符替换为另一个即可。 Replace each [ with an = , replace each , with an & , and remove all ] . 每个替换[= ,替换每个,& ,并删除所有]

 var str = "a[123],b[456],c[789]" var string = str.replace(/([az])\\[(\\d+)],?/g, '$1=$2&').slice(0, -1); alert(string); 

Brute force way im not good at Regex. 蛮力方式我不太擅长正则表达式。 Just adding my thoughts 只是添加我的想法

  var str = "a[123],b[456],c[789]" str = str.replace(/],/g, '&'); str = str.replace(/\\[/g, '='); str = str.replace(/]/g,''); alert(str); 

The simple 2 line answer for this is: 简单的两行答案是:

str=str.replace(/,/g,"&");
str=str.replace(/(\w)\[(\d+)\]/g,"$1=$2");

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

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