使用javascript解析网页时出错
我正在尝试使用javascript解析页面这是页面的一部分:使用javascript解析网页时出错,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试使用javascript解析页面这是页面的一部分: <div class="title"> <h1> Affect and Engagement in Game-BasedLearning Environments </h1> </div> 现在,我可以获得标题内的值,但显示的值前后都有很大的空间。我尝试使用替换函数替换空格,但没有出现re
<div class="title">
<h1>
Affect and Engagement in Game-BasedLearning Environments
</h1>
</div>
现在,我可以获得标题内的值,但显示的值前后都有很大的空间。我尝试使用替换函数替换空格,但没有出现replce。我不明白标题值前后都有什么。我想以某种方式删除多余的空间。因为您的已经在使用jQuery,您可以利用它们的
$.trim
函数删除前导和尾随空格
$(data).find('h1').each(function() {
console.log($.trim($(this).text()));
});
Reference:尝试使用Javascript的来去除两边的空白 函数的引用:
替换仅替换找到的第一个实例,它可能只删除了一个空格。。。请改用正则表达式语法尝试以下操作:
text.replace(/ /g, '');
这将删除所有空格,甚至是字符串文本中的空格。为了避免这种情况,您可能只希望替换双空格:
text.replace(/ /g, '');
此外,您可能需要删除新行:
text.replace(/\n/g, '');
这里有一个例子
如果您确实知道字符串的两端仅被空格包围,但希望保留其中的所有内容,则可以使用trim:
text.trim();
HTML实际上在
元素中包含这些空格,因此可以预期它们出现在.text()
的结果中
通常你只需要使用。但是,您可能也希望替换文本中的换行符
$(data).find('h1').each(function() {
var text = $(this).text();
// Replaces any multiple whitespace sequences with a single space.
// Even inside the text.!
// E.g. " \r\n \t" -> " "
text = text.replace(/\s+/g, " ");
// Trim leading/trailing whitespace.
text = text.trim();
console.log(text);
});
是的!这很有魅力。但我不想知道文本前后到底有什么。空白?@user3868494。它可以是换行符、空格(包括不间断空格)或制表符。任何一个或所有这些的组合都可能造成你所看到的空间。
$(data).find('h1').each(function() {
var text = $(this).text();
// Replaces any multiple whitespace sequences with a single space.
// Even inside the text.!
// E.g. " \r\n \t" -> " "
text = text.replace(/\s+/g, " ");
// Trim leading/trailing whitespace.
text = text.trim();
console.log(text);
});