使用正则表达式在div中获取部分类名和文本

时间:2018-07-01 10:52:02

标签: javascript regex dom domparser

我需要从此HTML中获取两个值,它们是toast-*的错误或成功,还需要在toast-message内获取值:

<div class="toast toast-error" style="">
    <div class="toast-message">You have failed.</div> 
</div>
<div class="toast toast-success" style="">
    <div class="toast-message">You have succeed. 
</div>

div元素一次仅显示一次,这可能是错误或成功。

有没有什么可以使用正则表达式的方法,所以我可以提取数组中的值,所以可以:

['success', 'You have succeed.']

['error', 'You have failed.']

任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:3)

您可以使用DOMParserquerySelector来选择元素。

let parser = new DOMParser();
let html = `<div class="toast toast-error" style=""><div class="toast-message">You have failed.</div></div>`;
let doc = parser.parseFromString(html, "text/html");
let div = doc.querySelector("div.toast");
let successOrFailure = div.getAttribute('class')
  .split(" ")
  .filter(word => word.substring(0, 6) === "toast-")[0]
  .substring(6);
let message = div.firstChild.innerHTML;
let result = [successOrFailure, message];
console.log(result);

答案 1 :(得分:1)

首选方法是使用源字符串,并借助DOM 测试元素是否存在:

const html1 = `
  <div class="toast toast-error" style="">
    <div class="toast-message">You have failed.</div>
  </div>  
`;

const html2 = `
  <div class="toast toast-success" style="">
    <div class="toast-message">You have succeed.</div>
  </div>
`;

/**
 * Returns the text of the error toast message.
 *
 * @returns {string|null} The toast message, or null if the elemenet is not present.
 */
function getErrorToastText(string) {
  const container = document.createElement('div');
  container.innerHTML = string;

  const toast = container.querySelector('.toast-error .toast-message');
  return toast ? toast.innerHTML : null;
}

/**
 * Returns the text of the success toast message.
 *
 * @returns {string|null} The toast message, or null if the elemenet is not present.
 */
function getSuccessToastText(string) {
  const container = document.createElement('div');
  container.innerHTML = string;

  const toast = container.querySelector('.toast-success .toast-message');
  return toast ? toast.innerHTML : null;
}


console.log('when .error-toast element present:', getErrorToastText(html1));
console.log('when .error-toast element not present:', getErrorToastText(html2));

console.log('when .success-toast element present:', getSuccessToastText(html2));
console.log('when .success-toast element not present:', getSuccessToastText(html1));

答案 2 :(得分:0)

有很多方法可以做到这一点。我只列出了其中三个,以查看全部check this answer

1。使用(ES6)JS函数includes

var str = "toast toast-success",
    substr = "success";
str.includes(substr);

2。使用indexOf

var str = "toast toast-success",
    substr = "success";
if(str.indexOf(substr) == 1){
    // the current div is a success
    // do your logic
}

3。使用正则表达式

// you get this string by getting class-list of the div
var str= "toast toast-success",         
    substr= /-success$/;   // or /-error$/
string.match(expr);