regex - Replicating Codeigniter's humanize() and underscore() function in Javascript -



regex - Replicating Codeigniter's humanize() and underscore() function in Javascript -

i'm trying replicate ci's humanize() , underscore() function in javascript.

from ci documentation, underscore() takes multiple words separated spaces , underscores them while humanize() takes multiple words separated underscores , adds spaces between them. ci implementation looks like:

function underscore($str) { homecoming preg_replace('/[\s]+/', '_', strtolower(trim($str))); } function humanize($str) { homecoming ucwords(preg_replace('/[_]+/', ' ', strtolower(trim($str)))); }

my code doesn't have replicate behavior exactly, underscore() function i'd able deal multiple whitespace characters, while humanize() function can bit looser , assume 1 underscore there separate each word.

so far have is:

function underscore(string) { string = $.trim(string).tolowercase(); var oldstring; while(oldstring !== string){ oldstring = string; string = string.replace(/\s+/, '_'); } homecoming string; } function humanize(string) { string = $.trim(string); var terms = string.split('_'); for(var i=0; < terms.length; i++){ terms[i] = terms[i].charat(0).touppercase() + terms[i].slice(1); } homecoming terms.join(' '); }

which works fine, yes, don't way did (it's way long compared php. there must more compact version), i'm wondering if there's more efficient / readable method accomplish this.

you can utilize g modifier replacement globally as:

function underscore(string) { string = $.trim(string).tolowercase(); homecoming string.replace(/\s+/g, '_'); }

javascript regex string

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -