从字符串内部的变量中提取值

时间:2019-01-08 23:08:36

标签: javascript jquery

为“短代码”提供了某些参数和动态值。需要使用javascript拉出这些值。 这是简码的样子 [提供按钮的宽度=“ 500px” bg =“#ff0000” color =“#3366ff” padding =“ 40px 50px” text =“加入!” font =“ 11px” weight =“ bold” style =“斜体”]

例如,我要提取width的值(在这种情况下为“ 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'

不确定我哪里出错了。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

尝试一下

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>

相关问题