简体   繁体   English

如何使用jQuery在HTML或XML文档的两个标签之间查找和替换文本?

[英]How to find and replace text in between two tags in HTML or XML document using jQuery?

I want to find and replace text in a HTML document between, say inside the <title> tags. 我想在HTML文档中查找和替换文本,例如在<title>标记内。 For example, 例如,

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? 有没有其他方法可以查找和替换HTML标签内的文本? Regex or may be using replaceWith() or something similar? 正则表达式或正在使用replaceWith()或类似的东西?

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> . 使星号“不是贪婪的”,因此找到</title>时它将停止(更快)。

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/

This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. 这将是使用Java的stristr(haystack, needle, bool)方法的绝佳时机。 First, you need to get the head of the document using $('head') , then get the contents using .innerHTML . 首先,您需要使用$('head')获取文档的.innerHTML ,然后使用.innerHTML获取内容。

For the sake of the answer, let's store $('head').innerHTML in a var called head . 为了得到答案,让我们将$('head').innerHTML在名为headvar 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. 首先,让我们使用stristr(head, '<title>', true)获取标题之前的所有内容,并使用stristr(head, '</title>') after ,并将它们存储在var beforeafter s中,分别。 Now, the final line is simple: 现在,最后一行很简单:

head.innerHTML = before + "<title>" + newTitle + after;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM