views:

34

answers:

3

...I should just list them:

  1. First 4 letters/numbers, with...
  2. All lowercase.
  3. Whitespace stripped.
  4. Symbols removed.

Should be simple. What's the best way to do this?

+1  A: 

Something like this?

"  MY STRING  ".replace(/^\s+|\s+$/g, '').substring(0,4).toLowerCase()

You can remove desired symbols with similar replace-method.

Epeli
+3  A: 
  1. slice(0, 4)
  2. toLowerCase()
  3. replace(/\s/g, '')
  4. replace(/[^\w\s]/g, '')

The third and fourth regexes can be combined more simply as just \W, to remove all non-alphanumerics, if that's what you want. If the ‘symbols’ you want to remove are more specific than that, you'll have to put them in a character class explicitly, eg. /[!"#...]/g. If you only mean that you want to remove whitespace at the start and end of a string (“trimming”):

replace(/^\s+/, '').replace(/\s+$/, '')

instead.(*)

Chain them together in whatever order is appropriate. If you want to chop to four characters after you've removed unwanted characters:

var processed= str.replace(/\W/g, '').toLowerCase().slice(0, 4);

(*: string.trim() is also available in ECMAScript Fifth Edition but not all browsers support it yet. You can hack trim() support into String.prototype if you would like to using string.trim() on all browsers today:)

if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return (''+this).replace(/^\s+/, '').replace(/\s+$/, '');
    };
}
bobince
Yes, I think I can work that into what I need. Thanks.
Hamster
A: 

Whitespace stripped.

only from the ends, or the whole string? The following strips all whitespace (and anything other than numbers and letters - \w includes underscores too) from the string.

str = str.replace(/[^a-z0-9]+/ig).substring(0, 4).toLowerCase();
Amarghosh