匹配字符串中的单词并使其小写

Match words in a string and make them lowercase

本文关键字:单词 字符串      更新时间:2023-09-26

我有一个示例字符串:

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之外的任何内容。

Asker发现这个链接有助于解决正则表达式问题:正则表达式匹配非英文字符?

只需使用.toLowerCase((.

var string = 'This is a süPer NICE Sentence, am I right?';
string = string.toLowerCase();
var words = string.split(' ');
//5 words maximum
words = words.slice(0,5);
console.log(words.join(', ')); //should print: this, is, super, nice, sentence

正则表达式过滤掉了特殊字符——如果你知道单词之间用空格分隔,只需使用string.split(''(;

只需将开头的字符串小写即可

string.toLowerCase().replace(...

或者,您可以使用array#map将单词数组映射为小写字符串。

console.log(words.map(function(word) { return word.toLowerCase(); }).join(', '));

您可以使用stringtoLowerCase方法首先将字符串转换为小写,然后对字符串执行所有需要执行的操作。

例如:var string = 'This is a suPer NICE Sentence, am I right?'.toLowerCase();