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

如何统计文本字符数?排除换行符的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:

  1. The element.trim() call doesn't modify the original element (strings in JavaScript are immutable) — you need to capture its return value to use the trimmed version.
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:11:39