In the following example:
<div id="mainDiv">
<h1>The <span class="bold">title</span></h1>
some text
<p>and again</p>
<p>another text.</p>
</div>
I'm trying to get all the text in one string. When I just do $('#mainDiv').text()
it returns the text as The titlesome textand againanother text
.
In this case I would like to have spaces between the words in child elements. So I came very close doing:
if ($('#mainDiv').find("*").length >= 1) {
$('#mainDiv').find("*").each(function () {
sFullText = sFullText + $(this).text().trim().replace(/\s\s+/g, ' ') + ' ';
});
}
The result now is: The titlesome textand again another text
.
So this works when all text is in child elements, but not if some text is in the mainDiv
. (the page and it's content is dynamic so I don't know what specific elements are in mainDiv
)
Using a jQuery plugin from here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
jQuery.fn.justtext = function() {
return $(this) .clone()
.children()
.remove()
.end()
.text();
};
// ...
var sFullText = $('#mainDiv').justtext();
if ($('#mainDiv').find("*").length >= 1) {
$('#mainDiv').find("*").each(function () {
sFullText = sFullText + ' ' + $(this).text().trim().replace(/\s\s+/g, ' ');
});
}
You can try your own code, but using a regex to replace one or multiple whitespace characters \\s
(check this definition ) with a single space one ' '
. Something like this:
$("#mainDiv").text().replace(/\s+/g, ' ')
You can check the example on this jsfiddle .
I believe your problem exists when you flatten down your html:
<div id="mainDiv" style="display:none;"><h1>The <span class="bold">title</span></h1>some text<p>and again</p><p>another text.</p></div>
<div id="result"></div>
$("#result").html($("#mainDiv").text());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.