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 ?
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"));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With