[Problem Solving + js] Processing of zero-width characters that are invisible but occupy a position

foreword

Blank strings appear in the project, but these blank strings cannot be filtered out using filters such as trim().

When printing content and length, it is blank + non-zero length.
Troubleshooting :
use charCodeAtprint each character to see their value

for (let i = 0; i < li.content.length; i++) {
    
    
  console.log(li.content[i], li.content.charCodeAt(i));
          }

The output result is: 8205, the number of times is the length, so the reason
is found : the string contains U+200D (zero-width connector)

Solution : Use regex to replace. li.content = li.content.replace(/\u200d/g, ''); // 去除零宽度连接符
In this way, the length of this blank string becomes 0, and it can be filtered out later.

problem solved.

Reference: chatgpt
removes ZERO WIDTH SPACE zero-width characters: invisible but occupying characters

Guess you like

Origin blog.csdn.net/sinat_41838682/article/details/130789509