gpt4 book ai didi

Javascript 正则表达式 : match first 50 characters, 关于单词

转载 作者:行者123 更新时间:2023-11-29 17:52:13 26 4
gpt4 key购买 nike

我试图通过匹配前 50 个字符然后连接“...”来保持一些导航栏行较短,但使用 substr 有时会产生一些尴尬的单词排骨。所以我想想办法尊重文字。

我可以编写一个函数来执行此操作,但我只是看看是否有更简单/更简洁的方法。

我已经在 perl 中成功地使用了它:

^(.{50,50}[^ ]*)

漂亮又优雅!但它在 Javascript 中不起作用:(

let catName = "A string that is longer than 50 chars that I want to abbreviate";
let regex = /^(.{50,50}[^ ]*)/;
let match = regex.exec(catName);

匹配 未定义

最佳答案

使用String#match使用正则表达式的方法 word boundary包括最后一个词。

str.match(/^.{1,50}.*?\b/)[0]

var str="I'm trying to keep some nav bar lines short by matching the first 50 chars then concatenating '...', but using substr sometimes creates some awkward word chops. So I want to figure out a way to respect words.";

console.log('With your code:', str.substr(0,50));
console.log('Using match:',str.match(/^.{1,50}.*?\b/)[0]);

关于Javascript 正则表达式 : match first 50 characters, 关于单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42421057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com