首页 > 解决方案 > 想要从字符串中获取值

问题描述

我有一个这样的字符串。

var test = "the email body text is <p>the email test is the email tes is the email.</p>
<p><span id="xXmergefield selnameXx5" class="tag mergefield selname" style="background-color: rgba(0, 0, 255, 0.75);" contenteditable="false" **data-replacement="{MERGEFIELD SailName}"**>Sail Name<em id="xXmergefield selnameXx5-remover" class="fas fa-times remover"></em></span></p>"

为了保存,我希望变量测试为,

var test = "the email body text is <p>the email test is the email tes is the email.</p>{MERGEFIELD SailName}".

代替 - -

<p><span id="xXmergefield selnameXx5" class="tag mergefield selname" style="background-color: rgba(0, 0, 255, 0.75);" contenteditable="false" data-replacement="{MERGEFIELD SailName}">Sail Name<em id="xXmergefield selnameXx5-remover" class="fas fa-times remover"></em></span></p>

-------- 我只想要属性数据替换的值- {MERGEFIELD SailName}。

最终结果必须是

var test = "the email body text is <p>the email test is the email tes is the email.</p>{MERGEFIELD SailName}".

标签: javascript

解决方案


像这样的东西?

var input = 'the email body text is <p>the email test is the email tes is the email.</p><p><span id="xXmergefield selnameXx5" class="tag mergefield selname" style="background-color: rgba(0, 0, 255, 0.75);" contenteditable="false" data-replacement="{MERGEFIELD SailName}">Sail Name<em id="xXmergefield selnameXx5-remover" class="fas fa-times remover"></em></span></p>'

var matches = input.match(/<p><span(.*?)<\/span><\/p>/g);
for(var i=0;i<matches.length;i++){
  var tag = matches[i].match(/data-replacement="(.*?)">/)[1];
  input = input.replace(matches[i],tag);
}

console.log(input);


推荐阅读