0

我正在尝试查找某些结果(可能超过 1 个)然后处理这些结果,但 /g 存在问题。似乎不想返回多个结果

我有以下代码

<div id="test"> 
<p> <!--{Byond:cta|localAction:contact|Contact Us}--><\/p> 
<p> &nbsp;<\/p> <p> <sub><strong>Important Information:<\/strong>&nbsp;Offer 
only available for new home loans. *Comparison Rate is calculated on a loan amount of 
$150,000 over a term of 25 years. **Minimum redraw of $500. ^Limits apply for fixed rate 
home loans.<\/sub><\/p> <!--{Byond:cta|localAction:product:45|Product}--> 
</div>

我正在尝试获取 byond 本地操作 amd 的每个实例,然后拆分字符串

我在用

var introduction = $("#test").html();
var initExpr = /<!--{Byond\:cta\|localAction[^}]+}-->/gm;
var initResult = initExpr.exec(introduction);


    // this result is always 1... WHY?
    var length = initResult.length;

    //based on the length split the results up

 for (var i = 0; i < length; i++) {
 var expr = /(?:<!--{Byond\:cta\|)(.*)\|(.*)(?:}-->)/i;
 var result = expr.exec(introduction);
 console.log(result[0], "String");
 console.log(result[1], "Local Action");
 console.log(result[2], "Button Name");


}

我只得到第一个结果的长度 1.. 应该是 2.. 然后需要使用它来计算拆分单个结果

谁能帮忙

4

1 回答 1

1

要获得所有匹配项,您必须将 exec() 方法放在一个 while 循环中。

你可以得到你正在寻找的结果:

<script type="text/javascript">
    var subject = document.getElementById('test').innerHTML;
    var pattern = /<!--\{Byond:cta\|([^|]+)\|([^|}]+)\}-->/g;
    var result = new Array();
    while( (match = pattern.exec(subject)) != null ) {
        result.push(match);
    }
</script>

您获得:

[["<!--{Byond:cta|localAction:contact|Contact Us}-->",
  "localAction:contact",
  "Contact Us"], 
 ["<!--{Byond:cta|localAction:product:45|Product}-->",
  "localAction:product:45",
  "Product"]]
于 2013-05-10T05:04:14.100 回答