如何提取数据属性的值

时间:2017-12-21 01:36:18

标签: javascript jquery regex

我有两个数据属性,我想获取数据属性的值。

<div class="message" data-error-message="password reset <p><b>The e-mail address you entered does not exist.</b><br></p>
<p>Check if you entered email correctly or&nbsp;<a href=www.gmail.com target="target">create a new account</a>.</p></div>

<div  data-error-message="email You can’t leave this field empty!"></div>

输出 =密码重置您输入的电子邮件地址不存在,电子邮件您不能将此字段留空。

var msg = jQuery('[data-error-message]').map(function() {
   return jQuery(this).data('error-message').replace(/<[^>]+>/g, '').replace(/(\r\n|\n|\r)/gm,"").replace("&nbsp;","").trim().split('.').join(' ');
}).get();
var msg = msg.join(',')
console.log(msg)

1 个答案:

答案 0 :(得分:0)

您可以创建内存节点并提取其文本。

&#13;
&#13;
var msg = jQuery('[data-error-message]').map(function() {
  var error = jQuery(this)
    .data('error-message')
    .replace(/\n|\r/g,'')
    .trim()
    .split('.')
    .join(' '),
    inmemory = $('<div/>', {
      html: error
    });
  return inmemory.text();
}).get();

var msg = msg.join(',')
console.log(msg)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="message" data-error-message="password reset <p><b>The e-mail address you entered does not exist.</b><br></p>
<p>Check if you entered email correctly or&nbsp;<a href=www.gmail.com target=target>create a new account</a>.</p>"></div>

<div data-error-message="email You can’t leave this field empty!"></div>
&#13;
&#13;
&#13;