Javascript Shortcode Parse

时间:2016-09-05 03:48:08

标签: javascript regex

我需要解析以下短代码,例如我的短代码是:

[shortcode one=this two=is three=myshortcode]

我希望这个 myshortcode 并添加到数组中以便:

['this', 'is', 'myshortcode']

注意:我通常知道标有&#34的短代码参数;和" (即[shortcode one =" this" two =" is" three =" myshortcode"]),但我需要解析上面的短代码,而不需要"& #34;

任何帮助真的很感激

4 个答案:

答案 0 :(得分:2)

我假设您要使用Regex解析第一个字符串并输出这三个元素,以便稍后将它们添加到数组中。这看起来很简单,还是我误解了你的需求?我假设单词shortcode与你的字符串一样。如果您尚未找到并隔离上面发布的短代码字符串,则可能需要两个正则表达式操作:

/\[shortcode((?: \S+=\S+)+)\]/

替换:"$1"

如果您已经准确地发布了代码,那么您可以跳过上面的正则表达式。无论如何,你将以以下正则表达式结束:

  / \S+=(\S+)(?:$| )/g

然后,您可以将所有匹配项添加到数组中。

如果这不是你想要的,那么你的代码可能会有一个更实际的例子。

答案 1 :(得分:0)

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);

您可以尝试以上代码。

答案 2 :(得分:0)

这是我的解决方案:https://jsfiddle.net/t6rLv74u/

首先,删除[shortcode并尾随]

接下来,按空格" "

拆分结果

之后,浏览数组并移除= .*?=之前和之前的所有内容。

现在你有了结果。

答案 3 :(得分:0)

在这里,我为您构建了一个完全可扩展的解决方案。该解决方案适用于任意数量的参数。



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;
}
&#13;
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
&#13;
&#13;
&#13;

相关问题