javascript - Converting ampersand (&) and blank space to a dash (-) in URLs using regex -
with code below, have converted following names url such
love & relationshipshttp://domain.org/love-relationshipscareer & guidancehttp://domain.org/career-guidancefilter('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 humanhttp://domain.org/being-humancompetitive examshttp://domain.org/competitive-examsfilter('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