javascript 如何使用 jQuery 在 HTML 或 XML 文档中的两个标签之间查找和替换文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20779071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find and replace text in between two tags in HTML or XML document using jQuery?
提问by Gandalf
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
我想查找和替换 HTML 文档中的文本,比如 <title> 标签内。例如,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
我尝试在 jQuery 中使用 parseXML()(下面的示例),但它不起作用:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
是否有不同的方法来查找和替换 HTML 标签内的文本?正则表达式或可能正在使用 replaceWith() 或类似的东西?
回答by James Gould
I did something similar in a question earlier today using regexes:
我在今天早些时候使用正则表达式在一个问题中做了类似的事情:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*?
means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>
.
那应该找到并替换它。[\s\S]*?
表示 [任何字符,包括空格和换行符] 任意次数,而 ? 使星号“不贪婪”,因此当它找到</title>
.
回答by Dimitar Dimitrov
You can also do something like this:
你也可以做这样的事情:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
这是一个小提琴:http: //jsfiddle.net/Z89dL/1/
回答by piticent123
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool)
method. First, you need to get the head of the document using $('head')
, then get the contents using .innerHTML
.
这将是使用 Javascriptstristr(haystack, needle, bool)
方法的好时机。首先,您需要使用 获取文档的头部$('head')
,然后使用获取内容.innerHTML
。
For the sake of the answer, let's store $('head').innerHTML
in a var
called head
. First, let's get everything before the title with stristr(head, '<title>', true)
, and what's after the title with stristr(head, '</title>')
and store them in var
s called before
and after
, respectively. Now, the final line is simple:
为了答案,让我们存储$('head').innerHTML
在一个var
被调用的head
。首先,让我们获取标题之前的所有内容 withstristr(head, '<title>', true)
以及标题之后的内容stristr(head, '</title>')
,并将它们分别存储在var
s 中调用before
和after
。现在,最后一行很简单:
head.innerHTML = before + "<title>" + newTitle + after;