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

JavaScript拆分字符串为两部分并保留完整单词(Pug环境)

在Pug中按完整单词拆分字符串为两部分

简便内联实现

直接在Pug模板中用正则匹配同时捕获拆分后的两部分,无需额外函数:

- // 目标字符串
- const str = `hello i am a very long string that needs to be split into two different parts! thank you so much for helping.`
- // 正则匹配:捕获前~70字符的完整单词部分,以及剩余内容
- const splitMatch = str.match(/^([\s\S]{70}[^\s]*)\s*(.*)$/s)
- // 处理边界情况:字符串长度不足70时直接返回原字符串和空值
- const str1 = splitMatch ? splitMatch[1] : str
- const str2 = splitMatch ? splitMatch[2] : ''

// 渲染结果
h1= str1
p= str2

正则说明

  • ^([\s\S]{70}[^\s]*):捕获第一部分,先取前70个任意字符([\s\S]兼容所有字符包括换行),再追加后续连续非空白字符,确保不会截断单词
  • \s*:跳过第一部分末尾的空白字符,避免剩余内容以空格开头
  • (.*):捕获剩余的所有内容
  • /s:修饰符让.匹配换行符,兼容多行字符串

可复用函数方案

如果需要在多个Pug模板中复用拆分逻辑,可以编写工具函数并导入:

1. 编写工具函数(比如stringUtils.js)

function splitByWord(str, maxLength = 70) {
  const regex = new RegExp(`^([\\s\\S]{${maxLength}}[^\\s]*)\\s*(.*)$`, 's')
  const match = str.match(regex)
  return match ? [match[1], match[2]] : [str, '']
}

module.exports = { splitByWord }

2. 在Pug中导入并使用

- const { splitByWord } = require('./stringUtils.js')
- const str = `hello i am a very long string that needs to be split into two different parts! thank you so much for helping.`
- const [str1, str2] = splitByWord(str)

h1= str1
p= str2

内联方式适合单次使用,函数方案更适配多场景复用需求。

内容的提问来源于stack exchange,提问作者Patryk Wieczorek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:39:46