【问题标题】:Pull values from variables inside a string从字符串中的变量中提取值
【发布时间】:2019-06-03 16:35:53
【问题描述】:

获得了包含某些参数和动态值的“简码”。需要使用 javascript 提取这些值。 这就是短代码的样子 [offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="进来吧!" font="11px" weight="bold" style="italic"]

例如,我想提取宽度值(在本例中为“500px”)。 我决定在 'width="' 和 '"' 之间拉一段字符串。不过,我无法摆脱一种感觉——一定有更好的方法。 这是我尝试的代码

<div class="shortcode">[offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!"  font="11px" weight="bold" style="italic"]</div>

var wholeshort = $(".shortcode").html();
var widthstart =  wholeshort.indexOf('width="') + 1;
var widthend = wholeshort.indexOf('"', widthstart);
var widthval = wholeshort.substring(widthstart,widthend);

有了这个,我得到 'idth=',而不是 '500px'

不知道我哪里出错了。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    只需使用正则表达式,并捕获一组中width=" 和以下" 之间的内容:

    const match = $(".shortcode").html().match(/width="([^"]+)"/);
    if (match) {
      console.log(match[1]);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="shortcode">[offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!"  font="11px" weight="bold" style="italic"]</div>

    【讨论】:

      【解决方案2】:

      试试这个

      let w = /width="(.*?)"/.exec(s)[1];
      

      其中s 包含您的字符串和数据,w 包含宽度值。

      let s= $(".shortcode").html();
      
      let w = /width="(.*?)"/.exec(s)[1];
      
      console.log(w);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div class="shortcode">[offer-button width="500px" bg="#ff0000" color="#3366ff" padding="40px 50px" text="Come on in!"  font="11px" weight="bold" style="italic"]</div>

      【讨论】:

      • 甜蜜!正是我需要的。谢谢!可以在 8 分钟内接受答案。
      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2021-05-27
      • 2012-09-09
      • 2019-07-22
      • 2013-08-28
      • 2020-12-27
      • 1970-01-01
      相关资源
      最近更新 更多