来自简码的 javascript 数组

标签 javascript regex shortcode

我需要一些帮助来从短代码构建数组。 问题出在匹配正则表达式部分。

我的短代码如下所示:

 [email_image,id=1,c=member,fS=15,lH=20]

期望的输出:

{name: 'email_image', id: '1', c: 'member', fS: '15', lH: '20'}

如何更改我的函数(regex)以使其工作?

谢谢。

function ajax(ed){

        var str = tinyMCE.activeEditor.getContent();
        var re = /\[email_image([^\]]*)\]/g;
        var found = str.match(re);

        found.map(function(item){
            //console.log(item);  //  [email_image,id=1,c=member,fS=15,lH=20] ....

            arraytophp = {name: 'email_image', id : item.split(',')[1].split('=')[1], c: item.split(',')[2].split('=')[1], fS : item.split(',')[3].split('=')[1], lH: item.split(',')[4].split('=')[1].replace(']','')};


            // PROBLEM START *************************************************************

            var arraytophp_test = {};
            item.match(/([\w-]+)=([^,]+)/g).forEach(function(attribute) {
                //console.log(attribute)
                attribute = attribute.match(/([\w-]+)=(.+?)/);
                arraytophp_test[attribute[1]] = attribute[2];
            });
            console.log(arraytophp_test);

            // PROBLEM END **************************************************************

            jQuery.ajax({
                url: "StringImage_Ajax/ajaxImage",
                type: "POST",
                dataType: "json",
                async:false,
                data: {"data" : JSON.stringify(arraytophp)}
                }).done(function(data){
                    string = data.string;
                    tinyMCE.activeEditor.setContent(tinyMCE.activeEditor.getContent().replace(item,string));    
                });
            });
    }

最佳答案

基本的 javascript 可以代替 RegEx,很好地完成此操作。

当然,RegEx 很棒,但有时它看起来就像用大锤砸开鸡蛋一样。

var item = '[email_image,id=1,c=member,fS=15,lH=20]';

var result = item.slice(1, -1).split(',').
    reduce(function (a,b) {
      var v=b.split('=');if(v.length===1) a.name=v[0];
      else a[v[0]]=v[1];return a}
,{});

console.log(result);

关于来自简码的 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39893686/

相关文章:

javascript - jQuery 延迟未被拒绝

javascript - Node js 使用中间件重定向太多重定向

javascript - 从 jquery() 移植的 dojo show() 和 hide()

java - 正则表达式:如何匹配可能有破折号的姓氏,但如果确实有破折号,则只能包含 1

wordpress - Wordpress Shortcode语法错误,意外 '}'

javascript - 根据另一个 Div 内容及其高度增加一个 Div 高度

javascript - 改进我可怕的 switch 正则表达式匹配语句

regex - Shell 脚本(用于移动文件的正则表达式)

具有多行参数的WordPress简码

WordPress Foreach 只显示一个结果