admin管理员组文章数量:1426201
...I should just list them:
- First 4 letters/numbers, with...
- All lowercase.
- Whitespace stripped.
- Symbols removed.
Should be simple. What's the best way to do this?
...I should just list them:
- First 4 letters/numbers, with...
- All lowercase.
- Whitespace stripped.
- 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
3 Answers
Reset to default 5slice
(0, 4)
toLowerCase
()
replace
(/\s/g, '')
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();
本文标签:
版权声明:本文标题:regex - Javascript, String formatting: I need the first 4 letters of a string, lowercase, whitespace skimmed, symbols removed - 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745394719a2656760.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论