gpt4 book ai didi

javascript - 匹配字符串中的单词并使它们小写

转载 作者:行者123 更新时间:2023-11-30 16:44:50 25 4
gpt4 key购买 nike

我有这个示例字符串:

var string = 'This is a süPer NICE Sentence, am I right?';

结果必须是:

this, is, süper, nice, sentence

要求:

  1. 最多 5 个字,
  2. 包含至少 2 个字符的单词
  3. 逗号分隔
  4. 处理特殊字符,如 ü 目前没有发生这种情况
  5. 全部为小写当前未发生这种情况

这是我当前的脚本:(你可以在 jsfiddle 中测试它)

var string = 'This is a süPer NICE Sentence, am I right?';
var words;
words = string.replace(/[^a-zA-Z\s]/g,function(str){return '';});
words = words.match(/\w{2,}/g);

if(words != null) {
//5 words maximum
words = words.slice(0,5);
if(words.length) {
console.log(words.join(', ')); //should print: this, is, süper, nice, sentence
}
}

join 之前将匹配的单词转换为小写的最佳方法是什么?

最佳答案

答案肯定是 toLowerCase(),但我认为运行它的最佳位置是在结尾而不是开头(要操作的项目较少):

if(words != null) {
//5 words maximum
words = words.slice(0,5);
if(words.length) {
console.log(words.join(', ').toLowerCase()); //here
}
}

据我所知,toLowerCase() 是 unicode 友好的。您的正则表达式正在剥离任何不是 a-z、A-Z 的内容。

提问者发现此链接有助于解决正则表达式问题:Regular expression to match non-English characters?

关于javascript - 匹配字符串中的单词并使它们小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31413448/

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