Created
October 3, 2011 19:32
-
-
Save lsauer/1260006 to your computer and use it in GitHub Desktop.
PHP's trim(chars) in JS and mapping RegExp matches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//author: lo sauer 2011 - lsauer.com | |
//implementation of PHP's trim | |
//see http://php.net/manual/en/function.trim.php | |
//bug: doesn't work with ']' in the charlist | |
//@param: charlist <string> | |
String.prototype.phptrim = function(s) | |
{ | |
if(0==arguments.length) | |
return this.valueOf().trim(); | |
//s = s.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1'); | |
var restr = '['+s.split('').join('|')+']*'; | |
var re = RegExp('^'+restr+'|'+restr+'$','g'); | |
return this.valueOf().replace(re,''); | |
} | |
//without a charlist provided: phptrim == trim, removes: | |
//you can with this code: "\x0B".trim().length, which should be 0 | |
//" " (ASCII 32 (0x20)), an ordinary space. | |
//"\t" (ASCII 9 (0x09)), a tab. | |
//"\n" (ASCII 10 (0x0A)), a new line (line feed). | |
//"\r" (ASCII 13 (0x0D)), a carriage return. | |
//"\0" (ASCII 0 (0x00)), the NUL-byte. | |
//"\x0B" (ASCII 11 (0x0B)), a vertical tab. | |
//Whitespace list: | |
//" \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000" | |
//Examples: | |
str = 'Hello I am {{name}}. Is it already the {{date}}...'; | |
str.match(/\{{2}([a-z0-9]*)\}{2}/gi). | |
>>>["{{name}}", "{{date}}"] | |
//with phptrim | |
str.match(/\{{2}([a-z0-9]*)\}{2}/gi).map(function(e){return e.phptrim('{}'); }) | |
//without phptrim | |
str.match(/\{{2}([a-z0-9]*)\}{2}/gi).map(function(e){return e.replace(/\{|\}/g,''); }) | |
>>>["name", "date"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment