使用jQuery去除HTML文本中多余空格的技术问题求助
Hey there! No worries at all about your English—totally get it, and there's no offense taken whatsoever 😊
The issue you're facing is that .trim() only removes whitespace from the start and end of your text string, but it doesn't handle the extra spaces (and line breaks) scattered throughout the content inside your .subTitle element. Here are a couple of straightforward fixes:
Solution 1: Replace Multiple Whitespaces with Single Spaces
Use a regular expression to match one or more whitespace characters (including spaces, tabs, and line breaks) and replace them with a single space, then trim the result to clean up any remaining leading/trailing spaces:
console.log($(".subTitle").text().replace(/\s+/g, ' ').trim());
Breakdown:
/\s+/g: The regex pattern where\smatches any whitespace character,+matches one or more occurrences, andgis the "global" flag to replace all matches (not just the first one)..replace(/\s+/g, ' '): Turns all groups of whitespace into a single space..trim(): Removes any remaining leading or trailing spaces from the final string.
Solution 2: Expected Clean Output
After applying the fix, your output will look clean and properly formatted, like this:
Location : "Chennai" => Designation : "Senior Graphic Artist" => END
Full Working Example
Here's the complete code to test this solution:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="subTitle"> <span class="attributeTitleContainer"> <strong><a class="Attribute" href="#">Location</a></strong>: <span class="attributeTitleValue"> "Chennai"</span> <span class="titleSeparator"> => </span> </span> <span class="attributeTitleContainer"> <strong><a class="Attribute" href="#">Designation</a></strong>: <span class="attributeTitleValue"> "Senior Graphic Artist"</span> <span class="titleSeparator"> => </span> </span> <span>END</span> </span> <script> console.log($(".subTitle").text().replace(/\s+/g, ' ').trim()); </script>
内容的提问来源于stack exchange,提问作者Karthik

