Andres SK
Andres SK

Reputation: 10974

Match words in a string and make them lowercase

I have this example string:

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

The result has to be:

this, is, süper, nice, sentence

Requirements:

  1. 5 words max,
  2. words that contain at least 2 characters
  3. comma separated
  4. takes care of special characters such as ü this is not currently happening
  5. all in lowercase this is not currently happening

This is my current script: (you can test it in 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
    }
}

What would be the best way to convert the matched words into lowercase before the join?

Upvotes: 1

Views: 893

Answers (5)

Gray
Gray

Reputation: 7130

The answer is definitely toLowerCase(), but I think the best place to run it is right at the end rather than the beginning (fewer items to operate on):

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

toLowerCase() is, as far as I know, unicode-friendly. Your regex is stripping anything not a-z,A-Z.

Asker found this link helpful for resolving regex issue: Regular expression to match non-English characters?

Upvotes: 1

asmockler
asmockler

Reputation: 187

Just use .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

The special characters were being filtered out by the regex - if you know the words are separated by a whitespace, just use string.split(' ');

Upvotes: 1

sahil gupta
sahil gupta

Reputation: 2349

You can use toLowerCase method of a string to first convert the string into lower case and then do all the manipulations you need to do on the string.

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

Upvotes: 0

Joey Robert
Joey Robert

Reputation: 7574

Alternatively, you could map the word array to a lowercase string using Array#map.

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

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Just lowercase the string from the start

string.toLowerCase().replace(...

Upvotes: 0

Related Questions