skip to Main Content

There are multiple solutions on StackOverflow to repace multiple characters in a string and from that I have this code:

var replaceChars = { ' ':'-', 'ń':'n', 'ó':'o', 'ż':'z', 'ą':'a' };
var answerStrUrl = answerStr.replace(/ń|ó|ż|ą/g,function(match) {return replaceChars[match];}).toLowerCase(); 

(answerStrUrl is defined earlier in the code)

This works for all the characters but what should I add in the second line so that spaces are replaced with ‘-‘

2

Answers


  1. Add the |s+| in the replace function.

    var answerStrUrl = answerStr.replace(/ń|ó|ż|s+|ą/g,function(match) {return replaceChars[match];}).toLowerCase();
    
    Login or Signup to reply.
  2. Build the regexp dynamically and use [] character group:

    const replaceChars = { ' ':'-', 'ń':'n', 'ó':'o', 'ż':'z', 'ą':'a' };
    
    const answerStr = 'ń ń ń ń ń';
    const regex = new RegExp(`[${Object.keys(replaceChars).join('')}]`, 'g');
    const answerStrUrl = answerStr.replace(regex, m => replaceChars[m]).toLowerCase(); 
    console.log(answerStrUrl);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search