我需要解析下面的短代码,例如,我的短代码是:
[shortcode one=this two=is three=myshortcode]我想让这个,是和myshortcode,然后添加到数组中,这样它就会:
['this', 'is', 'myshortcode']注意:我通常知道带有“and”标记的短代码参数(即one=--这个“two=”是“three=”myshortcode ),但我需要解析上面没有"“的短代码。
任何帮助都是非常感谢的
发布于 2016-09-05 05:11:47
给您,我已经为您构建了一个完全可伸缩的解决方案。该解决方案适用于任意数量的参数。
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>
发布于 2016-09-05 04:03:38
我假设您希望使用Regex解析第一个字符串并输出这三个元素,以便稍后将它们添加到数组中。这听起来很简单,还是我误解了你的需要?我假设单词shortcode将出现在您的字符串中。如果您还没有找到并隔离上面发布的短代码字符串,您可能需要两个regex操作:
/\[shortcode((?: \S+=\S+)+)\]/替换:"$1"
如果您已经有了与您发布的代码完全相同的代码,那么您可以跳过上面的正则表达式。无论如何,您将以以下regex结尾:
/ \S+=(\S+)(?:$| )/g然后,可以将所有匹配添加到数组中。
如果这不是您想要的,那么一个更真实的代码示例可能会有所帮助。
发布于 2016-09-05 04:29:55
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://stackoverflow.com/questions/39323653
复制相似问题