简体   繁体   English

正则表达式以匹配JavaScript中{和}之间的字符串?

[英]Regular expression to match string between { and } in javascript?

Given the following string, I tried to use regular expression match any string between just { and } , and surround it with <tr style="display:none;"><td></td></tr> . 给定以下字符串,我尝试使用正则表达式匹配{}之间的任何字符串,并用<tr style="display:none;"><td></td></tr>包围。

I tried write the following script but it does not work. 我尝试编写以下脚本,但不起作用。

 $(document).ready(function() { table = ` <table border="1"> {% Acount Summary 2018 %} <tbody> {I} <tr style="height: 25px;"> <td style="padding-left: 10px;">Account Number: </td> {# II #} <td>Account</td> {% Active Account %} </tr> { Requested Account #} <tr style="height: 25px"> <td style="padding-left: 10px;">Number of Requests: </td> <td>Request</td> {{ III }} </tr> {# <tr style="height: 25px"> <td style="padding-left: 10px;">Customer: </td> <td>Contract Customer</td> </tr> #} <tr style="height: 25px"> <td style="padding-left: 10px;"> Customoer ID</td> <td>ID</td> </tr> {# CustomerName #} </tbody> {# Account #} {{ Inactive }} </table> `; table.replace(/({\\s*?.*?.*})/g, '<tr style="display:none;"><td>$1</td></tr>'); console.log(table); $('#COA').html(table); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="COA"></div> 

What was missing? 缺少了什么? How could I correct script above to achieve above result? 我该如何纠正上面的脚本以达到上述效果? Thanks. 谢谢。

You need to reassign your variable table : 您需要重新分配变量table

table = table.replace( ... )

I edited your RegEx for it to be simpler and exclude the {} : {([^}]*)} 我对您的RegEx进行了编辑,以使其更加简单,并排除了{}{([^}]*)}

Note that your method won't handle the nested {} . 请注意,您的方法将不会处理嵌套的{} You would have to go the recursive road for it to do so. 为此,您必须走递归之路。

 $(document).ready(function() { table = ` <table border="1"> {% Acount Summary 2018 %} <tbody> {I} <tr style="height: 25px;"> <td style="padding-left: 10px;">Account Number: </td> {# II #} <td>Account</td> {% Active Account %} </tr> { Requested Account #} <tr style="height: 25px"> <td style="padding-left: 10px;">Number of Requests: </td> <td>Request</td> {{ III }} </tr> {# <tr style="height: 25px"> <td style="padding-left: 10px;">Customer: </td> <td>Contract Customer</td> </tr> #} <tr style="height: 25px"> <td style="padding-left: 10px;"> Customoer ID</td> <td>ID</td> </tr> {# CustomerName #} </tbody> {# Account #} {{ Inactive }} </table> `; table = table.replace(/{([^}]*)}/g, '<tr style="display:none;"><td>$1</td></tr>'); console.log(table); $('#COA').html(table); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="COA"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM