The solution to displaying only one space in html with multiple spaces in a row

Table of contents

1. Problems

Two, the solution

1. Style solution

2. Use regular replacement escape characters


1. Problems

Recently, I encountered a strange phenomenon in the project development. The user has stored data with three spaces in the middle of the database. The database is stored normally, and the data returned by the interface is also with three spaces. However, there is only one space in the page display. The phenomenon is as follows:

Then the test lady found me and said that there was data loss due to pasting and copying, and then. . . At once. . . Like to mention bugs.

Below I use two methods to solve this problem.

Two, the solution

1. Style solution

element add this style:

white-space:pre

Regarding white-space, the specific parameters are as follows:

value describe
normal default. Whitespace is ignored by the browser.
pre White space is preserved by the browser. It behaves like a tag in HTML.
nowrap The text will not wrap, the text will continue on the same line until a tag is encountered.
pre-wrap Whitespace sequences are preserved, but line breaks are performed normally.
pre-line Merge whitespace sequences, but preserve newlines.
you inherit Specifies that the value of the white-space attribute should be inherited from the parent element.

see the effect;

 2. Use regular replacement escape characters

If you want to display multiple characters on the page, you can use entity characters & internal fragments; instead of spaces, as follows: name

'三个   字符' // 中间显示三个空格

Then we can replace the spaces in the displayed variables with entity characters using regular expressions, as follows:

const str = '三个   字符';
str.replace(/\s/g, ' ') // "三个   字符"

important point:

After replacing it with entity characters, display the variable on the page with innerHtml, otherwise the browser cannot recognize it.

The problem is perfectly solved, YYDS! Welcome to communicate in the comment area.

If the article is helpful to you, ❤️Follow+Like❤️Encourage ! The blogger will continue to update. . . .

Online Blog: Fu Chaoyang's Blog

Guess you like

Origin blog.csdn.net/chaoPerson/article/details/131541902