How to remove extra spaces or characters from a string before displaying content?

Calendar 👁️ 62

During website operations, we often encounter unnecessary spaces, line breaks, or special characters in the content. These "impurities" not only affect the aesthetics of the content and the user's reading experience, but may also have a negative impact on the page layout and search engine optimization (SEO) sometimes.AnQiCMS (AnQiCMS) is an efficient content management system that provides flexible and powerful template functions, among which the built-in template filters are the tools to solve such problems.

When you want to clean up the string before displaying the content on the page, to remove unnecessary spaces or characters that are not needed, you do not need to modify the original data in the database, but simply use the appropriate filter at the template level, you can easily achieve this goal.

Understanding the question: Why do we need to remove extra characters?

Extra characters in the content may come from various sources:

  • Copy and pasteWhen copying content from other documents or web pages, it is common to bring in extra spaces, line breaks, or format characters.
  • Data importThere may be irregular characters in the source file when importing data in bulk.
  • Manual entry errorThe editor may accidentally press the space bar too many times or enter irrelevant characters during the entry process.

These seemingly minor issues, when accumulated, can lead to misalignment of page layout, inaccurate keyword density calculation, decline in user experience, and even affect the professional image of the website.Therefore, it is particularly important to master how to remove these 'impurities' in the template.

AnQiCMS's solution: powerful template filter

The Anqi CMS template engine supports filter syntax similar to Django, allowing you to apply various processing functions when outputting variables. These filters start with{{变量名|过滤器名称:参数}}The format using, they only affect the display of content, but will not modify the original data stored in the database, ensuring the integrity and security of the data.

Next, we will focus on several very practical filters for removing extra spaces or characters in strings.

1.trimSeries of filters: Remove leading and trailing whitespaces or specified characters from strings.

trimSeries filters are the ideal choice for processing "dirty data" at the beginning and end of strings.

  • trimFilterIt can remove all whitespace characters at the beginning and end of a string (including spaces, tabs, newlines, etc.).If you specify a parameter, it will remove all specified characters from both ends of the string.

    • Example: Remove extra spaces at the beginning and end of strings.
      
      {{ "   欢迎使用 安企CMS   "|trim }}
      {# 显示结果: "欢迎使用 安企CMS" #}
      
    • Example: Remove specific characters at the beginning and end of strings.
      
      {{ "---重要通知---"|trim:"-" }}
      {# 显示结果: "重要通知" #}
      
  • trimLeftFilter: withtrimSimilar, but it only clears the whitespace or specified characters from the left (beginning) of the string.

    • Example: Clears the whitespace at the beginning of the string.
      
      {{ "   左侧有空格"|trimLeft }}
      {# 显示结果: "左侧有空格 " #}
      
    • Example: Clears the specified characters at the beginning of the string.
      
      {{ "### 标题"|trimLeft:"#" }}
      {# 显示结果: " 标题" #}
      
  • trimRightFilter: withtrimLeftRelatively, it only clears the whitespace or specified characters at the end of the string.

    • Example: Clears the spaces at the end of the string.
      
      {{ "右侧有空格   "|trimRight }}
      {# 显示结果: "右侧有空格" #}
      
    • Example: Clears the specified characters at the end of the string.
      
      {{ "产品名称.zip"|trimRight:".zip" }}
      {# 显示结果: "产品名称" #}
      

2.cutFilter: Remove the specified character from any position in the string

When you need to remove all occurrences of a specific character from the string, no matter where they are located,cutThe filter comes into play.

  • ExampleRemove all commas from the string.
    
    {{ "苹果,香蕉,橘子"|cut:"," }}
    {# 显示结果: "苹果香蕉橘子" #}
    
  • ExampleRemove all hyphens (-) and underscores (_)
    
    {{ "产品-型号_V1.0"|cut:"-"|cut:"_" }}
    {# 显示结果: "产品型号V1.0" #}
    
    It should be noted that,cutThe filter removes characters directly, if it removes spaces, it will remove all spaces, including the single spaces between words that you may want to keep. Therefore, when dealing with spaces, you may need more refined control, which is where you would usereplacefilter.

3.replaceFilter: Replace specific characters or strings

replaceThe filter is the most powerful feature, allowing you to replace a substring with another in a string.This is very effective for standardizing formats, reducing redundant spaces, or deleting specific patterns of characters.

  • Usage method:{{ 变量|replace:"旧子串,新子串" }}Comma-separated between the 'old substring' and 'new substring'.

  • ExampleReplace all consecutive spaces in a string with a single space. Sometimes, a string may contain one or more consecutive spaces,replaceIt can help you normalize them.

    {{ "这是    一个   多余空格   的例子"|replace:"  "," " }}
    {# 显示结果: "这是  一个  多余空格  的例子" #}
    

    You may need to apply this filter multiple times to ensure that all consecutive spaces are replaced with a single space:

    {{ "这是    一个   多余空格   的例子"|replace:"  "," "|replace:"  "," "|replace:"  "," " }}
    {# 显示结果: "这是一个多余空格的例子" #}
    
  • Example: Remove specific symbols from the string, such as brackets.

    {{ "产品名称 (型号)"|replace:"(",""|replace:")","" }}
    {# 显示结果: "产品名称 型号" #}
    
  • ExampleReplace newline characters with spaces to display multi-line text as a single line.

    {{ "第一行\n第二行\n第三行"|replace:"\n"," " }}
    {# 显示结果: "第一行 第二行 第三行" #}
    

Combine usage with advanced techniques

These filters can be chained as needed, for example:

{% set dirty_content = "   ##  产品名称-型号 (V1.0)   \n\n  更多描述  " %}
{{ dirty_content|trim|replace:"  "," "|replace:"  "," "|cut:"#"|replace:"-"," "|replace:"(",""|replace:")",""|replace:"\n"," " }}
{# 预期显示结果: "产品名称 型号 V1.0 更多描述" #}

After processing the string, if the original content may contain HTML tags and you want the browser to parse these HTML correctly (instead of displaying them as plain text), remember to add it after all cleaning filters have been applied|safeFilter:

{% set html_content = "  <p>  一段 <b>格式化</b> 的文本。  </p>  " %}
{{ html_content|trim|replace:"  "," "|safe }}
{# 显示结果: <p> 一段 <b>格式化</b> 的文本。 </p> #}

Please notesafeThe position of the filter, it should be at the end of all string operations to ensure that the processed result is safely output as HTML.

By flexibly using these security CMS provided template filters, you can ensure that the display of website content remains tidy and professional, providing users with a better browsing experience, also

Related articles

How to concatenate or replace strings before displaying them?

In AnQiCMS (AnQiCMS) content operation, we often encounter the need to dynamically process strings displayed on the front end of the website.To enhance the user reading experience, optimize search engine inclusion, or maintain consistency in content display, flexibly concatenating or replacing strings is a very practical skill.AnQi CMS, with its efficient template engine based on Go language, provides us with powerful and convenient tools, making these operations easy to implement at the template level.String concatenation

2025-11-08

How to format floating-point numbers, controlling the number of decimal places displayed?

Website content operation, it is crucial to display numbers accurately, especially floating-point numbers such as prices and statistics, for enhancing user trust and page professionalism.AnQi CMS knows this, providing simple and flexible tools in its powerful template engine, allowing content creators to easily control the display format of floating-point numbers, including decimal places, without delving into complex programming.Next, we will discuss how to use built-in filters in Anqi CMS templates to elegantly format floating-point numbers.### Use `floatformat`

2025-11-08

How to truncate long text and display an ellipsis?

In website content presentation, we often need to refine some long text content, such as displaying abstracts on article list pages or showing brief descriptions on product cards.If the entire content is displayed directly, it may not only destroy the neat layout of the page, but may also affect the efficiency of users in quickly browsing information.Therefore, truncating long text and adding an ellipsis at the end has become a common strategy to improve user experience.AnQi CMS as an efficient content management system, built-in flexible template filters, can help us easily achieve this function

2025-11-08

How to safely display HTML or JS code in a template without escaping?

In AnQi CMS template development and content operations, sometimes we need to directly display HTML code or run JavaScript scripts on the page, rather than have them parsed by the browser as plain text.This usually occurs when it is necessary to embed third-party statistical code, advertisement scripts, or when displaying code examples in article content.However, AnQi CMS, for security reasons, defaults to escaping the content output to templates to prevent security vulnerabilities such as cross-site scripting (XSS).To safely display HTML or JS code in a template without being escaped

2025-11-08

How to debug variables in a template and display their structure and values?

During the development and maintenance of website templates, we often encounter such situations: a page element does not display as expected, or data seems missing or incorrectly formatted.This is the key to quickly locate the problem, as you can clearly view the structure and specific values of variables in the template.For users who use AnQiCMS, the system provides powerful and convenient debugging tools to help us easily "penetrate" template data.Why do we need to debug template variables? Data is passed through variables in the AnQiCMS template.

2025-11-08

How to convert the original image address to a thumbnail address for display?

In modern website operations, images play a crucial role, not only enhancing the attractiveness of the content but also effectively conveying information.However, very large image files can significantly slow down website loading speed, harm user experience, and even affect search engine rankings.Therefore, converting the original image address to an optimized thumbnail address for display is an important part of website performance optimization.AnQiCMS as an efficient content management system fully considers the needs of image processing, built-in powerful thumbnail generation and management functions.Configure and template calls reasonably

2025-11-08

How to customize the layout and content display of the article detail page in AnQi CMS?

AnQiCMS (AnQiCMS) is a highly flexible content management system that provides great freedom to content operators, especially in customizing the layout and content display of article detail pages.Understanding the underlying mechanism and operation methods can help us better create personalized pages that meet user needs and optimize SEO performance.Why do you need a custom article detail page?In website operation, the article detail page is not only a carrier of content, but also a key touchpoint for users to deeply interact with information and achieve conversion goals.The standardized template is convenient and fast

2025-11-08

How to use the `archiveList` tag to display the latest 10 article titles and summaries on the homepage?

In Anqi CMS, the homepage often plays a crucial role in displaying the latest content and attracting visitors' attention.If you want to clearly list the latest 10 article titles and summaries on the homepage, the `archiveList` tag is the powerful tool to achieve this goal.It is flexible and easy to use, helping you easily display dynamic content in the most prominent position on the website.We need to display the titles and summaries of the latest 10 articles on the homepage by using the `archiveList` tag's core parameters

2025-11-08