You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery去除HTML文本中多余空格的技术问题求助

Fixing Extra Spaces When Retrieving Text with jQuery

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 \s matches any whitespace character, + matches one or more occurrences, and g is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:57:16