【问题标题】:How can I remove all HTML elements from a string excluding a special class?如何从字符串中删除除特殊类之外的所有 HTML 元素?
【发布时间】:2020-03-20 17:49:13
【问题描述】:

我有问题。我目前正在寻找一种从字符串中删除任何 HTML 元素的方法。但有两个条件:

  1. 元素的内容应该保留
  2. 不应删除具有已定义类的特殊元素

我已经尝试了很多东西,并查看了很多关于 SO 的问题/答案,但不幸的是,我无法真正找出任何答案。不幸的是,这远远超出了我的能力。但我想知道这样的事情是如何工作的。

我尝试过的问题/答案: How to strip HTML tags from string in JavaScript?, Strip HTML from Text JavaScript

所以当我有一个这样的字符串时:

You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span>

剥离后应该是这样的:

You have to pay <div class="keep-this">$200</div> per month for your car

我实际上尝试过以下事情:

jQuery(document).ready(function ($) {
	let string = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span>';

	console.log(string);

	function removeHTMLfromString(string) {
		let tmp = document.createElement("DIV");

		tmp.innerHTML = string;
		return tmp.textContent || tmp.innerText || "";
	}

	console.log(removeHTMLfromString(string));

	console.log(string.replace(/<[^>]*>?/gm, ''));
});
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

我还尝试了一个正则表达式工具来查看删除了什么,但不幸的是,我在这里也没有取得太大进展:

https://www.regexr.com/50qar

如果有人可以帮助我完成这项任务,我会很高兴。非常感谢!

更新

也许有办法只用一个正则表达式?如果是,在使用此正则表达式时如何使用特殊类排除我的元素:/&lt;\/?[^&gt;]+(&gt;|$)/g

【问题讨论】:

  • 给定字符串的输出是什么?我的意思是You have to pay 的文字在哪里?
  • @SajeebAhamed 该死的,我忘了添加它。抱歉这个问题。
  • 每个问题都有解决方案。我已经更新了我的答案。希望能帮到你。

标签: javascript jquery html regex


【解决方案1】:

这可能是一个有点大的代码。但我认为它可能会对你有所帮助。

let str = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';

const el = document.createElement("div");
el.innerHTML = str;

// Get all the elements to keep
const keep = el.querySelectorAll(".keep-this");

// Replace the keeping element from the original string
// With special pattern and index so that we can replace
// the pattern with original keeping element
keep.forEach((v, i) => {
  const keepStr = v.outerHTML;
  str = str.replace(keepStr, `_k${i}_`);
});

// Replace created element's innerHTML by patternised string.
el.innerHTML = str;

// Get the text only
let stringify = el.innerText;

// Replace patterns from the text string by keeping element
keep.forEach((v,i) => {
  const keepStr = v.outerHTML;
  stringify = stringify.replace(`_k${i}_`, keepStr);
});

console.log(stringify);

如果有任何误导,请给我评论。

更新:正则表达式方法

使用正则表达式可以完成相同的任务。方法是-

  1. 通过正则表达式找到所有可保留的元素并存储它们。
  2. 用相同的模式替换输入字符串中的所有可保留元素
  3. 从字符串中删除所有 HTML 标记。
  4. 用可保留的元素替换相同的模式。

let htmlString = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> Another <div class="keep-this">$400</div> here';

// RegExp for keep elements
const keepRegex = /<([a-z1-6]+)\s+(class=[\'\"](keep-this\s*.*?)[\'\"])[^>]*>.*?<\/\1>/ig;

// RegExp for opening tag
const openRegex = /<([a-z1-6]+)\b[^>]*>/ig;

// RegExp for closing tag
const closeRegex = /<\/[a-z1-6]+>/ig;

// Find all the matches for the keeping elements
const matches = [...htmlString.matchAll(keepRegex)];

// Replace the input string with any pattern so that it could be replaced later
matches.forEach((match, i) => {
  htmlString = htmlString.replace(match[0], `_k${i}_`);
});

// Remove opening tags from the input string
htmlString = htmlString.replace(openRegex, '');

// Remove closing tags from the input string
htmlString = htmlString.replace(closeRegex, '');

// Replace the previously created pattern by keeping element
matches.forEach((match, index) => {
  htmlString = htmlString.replace(`_k${index}_`, match[0]);
})

console.log(htmlString);

【讨论】:

  • 感谢您的代码!你认为不创建临时元素有可能吗?
【解决方案2】:

如果日期和车辆 div 和 class 来自另一个函数,您应该从那里删除它。

【讨论】:

  • 不。它来自一个字符串。
  • 那个代码有点大,你有没有尝试使用 getElementsByTabName() 方法?虽然看起来你的问题已经解决了。
猜你喜欢
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 2014-02-22
  • 2011-09-27
相关资源
最近更新 更多