【问题标题】:Javascript RegExp Selector for HTML Template Strings用于 HTML 模板字符串的 Javascript RegExp 选择器
【发布时间】:2016-06-26 18:55:34
【问题描述】:

我需要一些关于我的 JavaScript 正则表达式的帮助。我需要一种方法来选择以下内容:

${user.name}
${user.age}

来自以下 html:

<tr>
    <td>${user.name}</td>
    <td>${user.age}</td>
</tr>

可能有多个 &lt;td&gt; 具有不同的值,并且字符串的“用户”部分并不总是用户。可以是任何东西。

理想情况下,我希望它们作为一个数组返回,尽管目前我会满足于任何东西。

【问题讨论】:

  • 处理给定 DOM 片段的表格单元格集合而不是将整个片段作为字符串处理,难道不是更好的方法吗?

标签: javascript html regex templates


【解决方案1】:

我不是正则表达式专家,但我希望它能起作用。

var str = "your html"
var matches = str.match(/\${[a-zA-Z0-9.]+}/g);

对于您给定的输入 html,输出将是

["${user.name}", "${user.age}"]

【讨论】:

    【解决方案2】:

    我写这个函数是为了你的目的:

        /**
         * This function assumes html with template syntax as a argument
         * and returns array from this marks.
         * Example of usage:
         *  If you have html markup like this:
         *   <table>
         *    <tr>
         *     <td>${user.name}</td>
         *     <td>${user.age}</td>
         *   </tr>
         *  </table>
         *
         * and call function with document.body.innerHTML as a argument
         *  console.log(getTemplates(document.body.innerHTML.toString()));
         * You will get the following result:
         *  Array [ "${user.name}", "${user.age}" ]
         *
         * @param input html string with template marks - ${variable.name}
         * @returns {Array} - all marks
         * @author Georgi Naumov
         * gonaumov@gmail.com for contacts and suggestions.
         */
        function getTemplates(input) {
            return (input.match(/\$\{[^}\s]+\}/g) || []);
        }
        console.log(getTemplates(document.body.innerHTML.toString()));
    

    你会得到这种形式的结果:

    Array [ "${user.name}", "${user.age}" ]
    

    【讨论】:

      【解决方案3】:
      var
        //  \$\{    ... search for occurrence of template string opener sequence,
        //  ([^.]+) ... then memorize every character (at least one) that is not a dot,
        //  \.      ... look for a single dot - the divider of your template string's sub-domains,
        //  ([^.]+) ... then again memorize every character that is not a dot,
        //  \}      ... finally identify the template string delimiter sequence.
        regXTemplateString = (/\$\{([^.]+)\.([^.]+)\}/),
      
        // make array from any derived html table cell element collection.
        tableCellList = Array.from(yourTableRowHTMLElement.getElementsByTagName('td')),
      
        // reduce table cell array to a data structure that one can work with further
        viewList = tableCellList.reduce(function (collector, tdElement) {
          var
            executedTemplate = regXTemplateString.exec(tdElement.innerHTML);
      
          if (executedTemplate) {
      
            collector.push({
              templateElement : tdElement,            // the html element reference
              domainName      : executedTemplate[1],  // e.g. "user" from "${user.name}"
              identifier      : executedTemplate[2]   // e.g. "age"  from "${user.age}"
            });
          }
          return collector;
      
        }, []);
      
      // do whatever you're pleased with `viewList`.
      

      【讨论】:

        【解决方案4】:

        这样的事情可能会帮助你:

        str = str.match(/\$\{\w*\.\w*\}/g);
        

        查看匹配Regex的示例

        var str = "<tr><td>${user.name}</td><td>${user.age}</td></tr>";
        str = str.match(/\$\{\w*\.\w*\}/g);
        console.log(str)

        解释:

        • \$ 匹配字符 $ 字面意思
        • \{ 匹配字符 { 字面意思
        • \w* 匹配任意单词字符 [a-zA-Z0-9_]
          • 量词:* 介于零和无限次之间,尽可能多次,按需回馈[贪婪]
        • \. 匹配字符 . 字面意思
        • \w* 匹配任意单词字符 [a-zA-Z0-9_]
          • 量词:*在零到无限次之间,尽可能多次,按需回馈[贪心] \} 匹配字符 } 字面意思
        • g 修饰符:全局。所有比赛(第一场比赛不返回)

        【讨论】:

          猜你喜欢
          • 2021-01-07
          • 2021-04-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-25
          • 2016-06-21
          • 2014-11-10
          • 1970-01-01
          相关资源
          最近更新 更多