最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript, String formatting: I need the first 4 letters of a string, lowercase, whitespace skimmed, symbols removed -

programmeradmin3浏览0评论

...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?

...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?

Share Improve this question asked Jul 10, 2010 at 9:26 HamsterHamster 5772 gold badges7 silver badges13 bronze badges 2
  • Have you given the correct order of these operations? For example, if you have "A B C D", if you follow your rules you get "ab". Somehow I think you might want "abcd" though. – Joseph Mansfield Commented Jul 10, 2010 at 9:34
  • Ah, right. Yeah I need the whitespace and symbols stripped before pressing to 4 characters. Thanks. – Hamster Commented Jul 10, 2010 at 9:40
Add a ment  | 

3 Answers 3

Reset to default 5
  1. slice(0, 4)
  2. toLowerCase()
  3. replace(/\s/g, '')
  4. replace(/[^\w\s]/g, '')

The third and fourth regexes can be bined 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+$/, '');
    };
}

Something like this?

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

You can remove desired symbols with similar replace-method.

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();

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论