D
D
Daniil Borovkov2015-10-18 18:58:49
JavaScript
Daniil Borovkov, 2015-10-18 18:58:49

How to use regular expressions correctly?

There is a task: Given a string. With the help of magic manipulations in JS, you need to make sure that all the first characters of the words are in upper case, and all the rest are in lower case. I feel with my butt that you can’t do without RegExp, I applied it. There is even an almost perfectly working code:

function titleCase(str) {
    var str = str.toLowerCase().replace(/\b./g, function(m){
        return m.toUpperCase();
    });
    return str;
}

titleCase("I'm a little tea pot");
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT");

But here's the problem: in the first case, instead of
"I'm"
displays
I'M
. How to fix?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Latyshev, 2015-10-18
@daniilborovkov

function titleCase(str) {
    var str = str.toLowerCase().replace(/\s[a-zA-Z]/g, function(m){
        return m.toUpperCase();
    });
    return str[0].toUpperCase() + str.substr(1);
}

UPD: This is for the case when the beginning of the word is the character immediately after the space character (space, tab, newlines)

I
Ivanq, 2015-10-18
@Ivanq

You're stupid!
Regular expressions are not needed here - you can do without
UPD As I understand it, an apostrophe is the beginning of a word. I found a similar topic on Google, but forgot where

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question