Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace characters or words in a string using javascript even with no space between them?

Tags:

javascript

I have a function something like this :

 var exchange = function(code) {
     var ref = {
       'one' : '1' , 
       'two' : '2' ,
       'three' : '3'
     }; 
   return code.split(' ').map( function (a) { 
     return a.split(' ').map( function (b) { 
        return ref[b]; 
     }).join(''); 
   }).join(' '); 
 };

So now I do it :

 var strg = "one two three";
 alert( exchange( strg ) ); // => 123

It works fine but I have a problem. Let me explain. I want it to execute same as now till with no space between.

For example :

 var strg = "onetwothree";
 alert( exchange( strg ) ); // => Nothing

But I want it to change the text even with no spaces. How can I do that ?

like image 680
Debarchito Avatar asked Oct 08 '19 16:10

Debarchito


2 Answers

You could create a regular expression with a joined string with pipe and replace found string with the values.

var exchange = function(code) {
        var ref = { one: '1',  two: '2', three: '3' }; 
        return code.replace(new RegExp(Object.keys(ref).join('|'), 'ig'), k => ref[k]);
    };

console.log(exchange("onetwothree"));
like image 72
Nina Scholz Avatar answered Oct 13 '22 00:10

Nina Scholz


You can iterate over number values and replace them.

 var exchange = function(code) {
     var ref = {
       'one' : '1' , 
       'two' : '2' ,
       'three' : '3'
     }; 
   Object.keys(ref).forEach(k => code = code.replace(k, ref[k]))
  return code
 };
 var strg = "onetwothree";
 alert( exchange( strg ) ); // => 123
like image 38
yaya Avatar answered Oct 13 '22 02:10

yaya