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

Match words in a string and make them lowercase

我有这个示例字符串:

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 之前将匹配的单词转换为小写的最佳方法是什么?

将字符串从头开始小写

string.toLowerCase().replace(...

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

console.log(words.map(function(word) { return word.toLowerCase(); }).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 的内容。

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

只需使用 .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(' ');

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

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