element.text().replace(/\s+/g, " ");
This uses a regular expression (/.../
) to search for one or more (+
) whitespace characters (\s
) throughout the element's text (g
, the global modifier, which finds all matches rather than stopping after the first match) and replace each with one space (" "
).