在[]括号上拆分字符串 [英] Split string on [] brackets

查看:99
本文介绍了在[]括号上拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串是某些输入字段的名称。示例:

the string is the name of some input fields. Examples:

a [b] [c]

x [y] [z] []

我正在尝试从中生成多维数组。

I'm trying to produce multidimensional arrays from it.

abc = value

xyz = [value] (值是一个数组,因为 []

x.y.z = [value] (value is an array because of [])

无论如何我对如何做到这一点有一些想法,但首先我需要将字符串拆分为包含所有键和子键的数组。

anyway i have some ideas on how to do that but first I need to split the string into an array that contains all keys and subkeys.

搜索谷歌我已经想出这个

Searching google I've come up with this

var parts = inputName.match(/[^\[\]]+/g);

它让我 [a,b,c] ,但在第二个例子中,我得到 [x,y,z] 而不是 [x,y,z,null]

it gets me [a,b,c], but on the 2nd example I get [x,y,z] instead of [x,y,z, null]

任何方式我都可以匹配 [] 并将其作为null添加到列表中?我对正则表达式并不熟悉

Any way I can also match [] and add it to the list as null ? I'm not that familiar with regular expressions


@AnnaK。为什么不能简单地使用ID和密钥发送
信息?它是一个动态的形式吗?是因为
你正在开发一个需要动态的框架吗?是因为
你在多个地方使用一个函数?你不能用
使用名字来序列化吗?我们不能给你建议,因为我们仍然没有
知道为什么你需要将它作为一个数组转移(无论如何都是
序列化),我们仍然不知道你的表格看起来是什么喜欢

@AnnaK. Why can't you simply use ids and keys to send your information? Is it a form that is dynamic in its size? Is it because you're developing a framework that needs to be dynamic? Is it because you're using a function multiple places? Can't you serialize it by using the names? We can't give you suggestions because we still don't know why you need to transfer it as an array (which would be serialized anyway), and we still don't know what your form looks like

因为我正在尝试使用Ajax发送表单数据。此外,在我发送数据之前,我需要预先添加一些我用javascript创建的字段。我无法序列化它,至少不能用 jQuery.serializeArray 如果这就是你的意思,因为如果我有多个键,比如 x [y] [z ] [] ,只会显示最后一个

Because I'm trying to send the form data with Ajax. Also, before I send the data, I need to prepend a few fields that I create with javascript. I cannot serialize it, at least not with jQuery.serializeArray if that's what you meant, because if I have multiple keys like x[y][z][], only the last one will appear

推荐答案

您可以使用以下解决方案:

You can use the following solution:

var parts = inputName.split(/[[\]]{1,2}/);
parts.length--; // the last entry is dummy, need to take it out

console.log(parts); // ["x", "y", "z", ""] 

如果您需要null值(因为有处理你无法控制)例如你可以使用这个片段来更新结果(cuTesy of @Ties):

If you need the null value (because there is processing you have no control over for example) you can use this snippet to update the result (curtesy of @Ties):

parts = parts.map(function(item){ return item === '' ? null : item });

这篇关于在[]括号上拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆