opensas
opensas

Reputation: 63395

Regular expression to replace words preserving spaces

I'm trying to develop a function in javascript that get a phrase and processes each word, preserving whiteSpaces. It would be something like this:

properCase('  hi,everyone   just  testing') => '  Hi,Everyone   Just  Testing'

I tried a couple of regular expressions but I couldn't find the way to get just the words, apply a function, and replace them without touching the spaces.

I'm trying with

'  hi,everyone   just  testing'.match(/([^\w]*(\w*)[^\w]*)?/g, 'x')
["  hi,", "everyone   ", "just  ", "testing", ""]

But I can't understand why are the spaces being captured. I just want to capture the (\w*) group. also tried with /(?:[^\w]*(\w*)[^\w]*)?/g and it's the same...

Upvotes: 2

Views: 872

Answers (4)

vol7ron
vol7ron

Reputation: 42089

I'm unclear about what you're really after. Why is your regex not working? Or how to get it to work? Here's a way to extract words and spaces in your sentence:

var str   = '  hi,everyone   just  testing';
var words = str.split(/\b/);   // [" ", "hi", ",", "everyone", " ", "just", " ", "testing"]
words     = word.map(function properCase(word){ 
                        return word.substr(0,1).toUpperCase() + word.substr(1).toLowerCase();
            });
var sentence = words.join(''); // back to original

Note: When doing any string manipulation, replace will be faster, but split/join allows for cleaner, more descriptive code.

Upvotes: 0

Michal Brašna
Michal Brašna

Reputation: 2323

What about something like

'  hi,everyone   just  testing'.replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});

If you want to process each word, you can use

'  hi,everyone   just  testing'.replace(/\w+/g, function(word) {
    // do something with each word like
    return word.toUpperCase();
});

Upvotes: 3

acarlon
acarlon

Reputation: 17264

See here: jsfiddle

function capitaliseFirstLetter(match)
{
    return match.charAt(0).toUpperCase() + match.slice(1);
}

var myRe = /\b(\w+)\b/g;
var result = "hi everyone,     just testing".replace(myRe,capitaliseFirstLetter);
alert(result);

Matches each word an capitalizes.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816262

When you use the global modifier (g), then the capture groups are basically ignored. The returned array will contain every match of the whole expression. It looks like you just want to match consecutive word characters, in which case \w+ suffices:

>>> '  hi,everyone   just  testing'.match(/\w+/g)
["hi", "everyone", "just", "testing"]

Upvotes: 1

Related Questions