如何统计文本字符数?排除换行符的JavaScript实现求助
Hey there! Let's get that character count working the way you want it to.
First, let's break down why your current code isn't skipping newline characters:
- The
element.trim()call doesn't modify the originalelement(strings in JavaScript are immutable) — you need to capture its return value to use the trimmed version. - Using
split(" ")doesn't handle newline characters at all, so any line breaks embedded in your text will still be included in the element lengths you're adding up.
Here are a couple of straightforward solutions depending on your exact needs:
Option 1: Just exclude newline characters (keep spaces)
If you want to count all characters except newlines (including spaces), this is the simplest approach:
// First, remove all newline/return characters from the text const textWithoutNewlines = body.replace(/[\n\r]/g, ''); // Now get the length of the cleaned text const length = textWithoutNewlines.length;
Option 2: Exclude newlines AND extra spaces (match your original code's intent)
If you were trying to count only non-space, non-newline characters (like your original split/trim logic suggests), you can combine cleaning newlines with your existing flow (and fix the trim issue):
let length = 0; // Strip out newlines first const cleanedBody = body.replace(/[\n\r]/g, ''); cleanedBody.split(" ").forEach(element => { // Capture the trimmed value since trim() doesn't change the original element const trimmedElement = element.trim(); length += trimmedElement.length; });
Or a more concise version using array methods:
const length = body .replace(/[\n\r]/g, '') .split(" ") .map(el => el.trim()) .reduce((total, trimmedEl) => total + trimmedEl.length, 0);
The regex [\n\r] covers both Unix-style newlines (\n) and Windows-style line breaks (\r\n), so it works across all platforms.
内容的提问来源于stack exchange,提问作者Mike K

