javascript - Converting ampersand (&) and blank space to a dash (-) in URLs using regex -
with code below, have converted following names url such
love & relationships
http://domain.org/love-relationships
career & guidance
http://domain.org/career-guidance
filter('amptodash', function(){ return function(text){ return text ? string(text).replace(/ & /g,'-'): ''; }; }).filter('dashtoamp', function(){ return function(text){ return text ? string(text).replace(/-/g,' & '): ''; }; })
however, have new set of names , can't figure out how both @ same time.
being human
http://domain.org/being-human
competitive exams
http://domain.org/competitive-exams
filter('amptodash', function(){ return function(text){ return text ? string(text).replace(/ /g,'-'): ''; }; }).filter('dashtoamp', function(){ return function(text){ return text ? string(text).replace(/-/g,' '): ''; }; })
how combine both regex codes can work hand in hand?
it looks want change instances of ampersand leading or trailing white-space or white-space single hyphen. if so, use following expression :
// replace strings have leading , trailing spaces or series of spaces string(text).replace(/(\s+&\s+|\s+)/g,'-'): '';
example
var input = ['love & relationships', 'career & guidance', 'being human', 'competitive exams']; (var in input) { var phrase = input[i]; console.log(phrase + ' -> ' + phrase.replace(/(\s+&\s+|\s+)/g, '-')); }
Comments
Post a Comment