[英]Javascript Shortcode Parse
我需要解析以下简码,例如我的简码是:
[shortcode one=this two=is three=myshortcode]
我想得到this , is和myshortcode并添加到数组中,这样它将:
['this', 'is', 'myshortcode']
注意:我通常都知道用“和”标记的简码参数(即[shortcode one =“ this” two =“ is” three =“ myshortcode”]),但是我需要解析上面没有“”的简码
任何帮助真的很感激
我假设您想使用Regex解析第一个字符串并输出这三个元素,以便稍后将它们添加到数组中。 这似乎很简单,还是我误会了您的需求? 我假设单词shortcode
与您的字符串中的一样。 如果尚未找到并隔离上面发布的shortcode字符串,则可能需要两个正则表达式操作:
/\[shortcode((?: \S+=\S+)+)\]/
替换: "$1"
如果您已经拥有与发布代码完全相同的代码,则可以跳过上面的正则表达式。 无论如何,您将使用以下正则表达式结束:
/ \S+=(\S+)(?:$| )/g
然后,您可以将所有匹配项添加到阵列中。
如果这不是您想要的内容,那么也许您的代码更真实的示例会有所帮助。
var str="[shortcode one=this two=is three=myshortcode]";
eval('var obj=' + str.replace(/shortcode /,"").replace(/=/g,"':'").replace(/\[/g,"{'").replace(/\]/g,"'}").replace(/ /g,"','"));
var a=[];
for(x in obj) a.push(obj[x]);
console.log(a);
您可以尝试上面的代码。
这是我的解决方案: https : //jsfiddle.net/t6rLv74u/
首先,删除[shortcode
和结尾]
接下来,用空格" "
分隔结果
之后,遍历数组并删除=, .*?=
之前和之后的所有内容。
现在您有了结果。
在这里,我为您构建了一个完美的可扩展解决方案。 该解决方案适用于任意数量的参数。
function myFunction() { var str = "[shortcode one=this two=is three=myshortcode hello=sdfksj]"; var output = new Array(); var res = str.split("="); for (i = 1; i < res.length; i++) { var temp = res[i].split(" "); if(i == res.length-1){ temp[0] = temp[0].substring(0,temp[0].length-1); } output.push(temp[0]); } document.getElementById("demo").innerHTML = output; }
<button onclick="myFunction()">Try it</button> <p id="demo"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.