Cleaning Up Whitespace In JavaScript Strings
Often when checking text in JavaScript UIs, lots of unnecessary whitespace is included. This is most prominent when checking the results of HTML elements. For example, text could be generated like this:
<div class='score-section' id='score'> <p id='graphics-score'>8</p> - <p id='sound-score'>7</p> - <p id='immersion-score'>9</p> - <p id='total-score'>9</p> </div>
With all the contents in the ids being filled in dynamically via calculations and server data. To test the UI, each score could be individually checked, but that would be a lot of selectors just to check a simple score. Instead the score id can be used with innerText (jquery equivalent text()), but that gives results like:
// With: document.querySelector("#score").innerText' the text // retrieved would be: const text = '8\n\n-\n7\n\n-\n9\n\n-\n9\n\n'; console.log(text); // 8 // // - // 7 // // - // 9 // // - // 9 //
Though this can be fixed with a simple whitespace replace:
console.log(text.replace(/\s+/g, ' ')); // 8 - 7 - 9 - 9
The g replaces text globally and the right hand part just replaces what was found on the left with a single space. s+ means any one or more whitespace character which includes tabs, new lines, double spaces and so on.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/removeWhitespace.js











