如何使用jQuery在HTML或XML文档中的两个标记之间查找和替换文本? [英] How to find and replace text in between two tags in HTML or XML document using jQuery?

查看:99
本文介绍了如何使用jQuery在HTML或XML文档中的两个标记之间查找和替换文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在< title>内部找到并替换HTML文档中的文本,标签。例如,

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,

var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";

我在jQuery中使用parseXML()(下面的示例),但它不工作: p>

I tried using parseXML() in jQuery (example below), but it is not working:

var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();

是否有其他方法可以在HTML标签中查找和替换文本?正则表达式或可能使用replaceWith()或类似的东西?

Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?

推荐答案

我今天早些时候使用正则表达式做了类似的事情: / p>

I did something similar in a question earlier today using regexes:

str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');

应该找到并替换它。 [\s\S] *?意味着[包括空格和换行符的任何字符]任意次数,使星号不贪心,因此它会在找到< / 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>.

这篇关于如何使用jQuery在HTML或XML文档中的两个标记之间查找和替换文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆