How to replace characters or words in a string using javascript even with no space between them?
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
I think likely the best thing to do is to create a standard parser constructor that goes character by character and then provide it a configuration and a function wrapper.
Constructor
//Parsing input output constructor;
function ParseFor( i, o ) {
this.str = i;
this.indexLength = this.str.length - 1;
this.arr = [ ...i ];
this.pointer = 0;
this.output = o;
this.match = false;
this.reset = function() {
this.pointer = 0;
this.match = false;
}
this.next = function( c ) {
if ( this.arr[ this.pointer ] === c ) {
if ( this.pointer === this.indexLength ) {
this.match = true;
} else {
this.pointer++;
}
} else {
this.reset();
}
return this;
}
}
Parse Work with RegEx and Constructor
let parsers = [];
for ( let [ k, v ] of Object.entries( ref ) ) parsers.push( new ParseFor( k, v ) );
let parsedStr = str.replace( /./g, ( c ) => {
let output = "";
parsers = parsers.map( parser => parser.next( c ) );
parsers.forEach( parser => {
if ( parser.match ) {
parser.reset();
output = parser.output;
}
} );
return output;
} );
Parse Function Wrapper
function parseStr( str, ref ) {
//... PARSE CONSTRUCTOR
//... PARSE WORK
return parsedStr;
}
parseStr( "onetwothree", {
'one': '1',
'two': '2',
'three': '3'
});
EXAMPLE:
function parseStr( str, ref ) {
//Parsing input output constructor;
function ParseFor( i, o ) {
this.str = i;
this.indexLength = this.str.length - 1;
this.arr = [ ...i ];
this.pointer = 0;
this.output = o;
this.match = false;
this.reset = function() {
this.pointer = 0;
this.match = false;
}
this.next = function( c ) {
if ( this.arr[ this.pointer ] === c ) {
if ( this.pointer === this.indexLength ) {
this.match = true;
} else {
this.pointer++;
}
} else {
this.reset();
}
return this;
}
}
//parse work
let parsers = [];
for ( let [ k, v ] of Object.entries( ref ) ) parsers.push( new ParseFor( k, v ) );
let parsedStr = str.replace( /./g, ( c ) => {
let output = "";
parsers = parsers.map( parser => parser.next( c ) );
parsers.forEach( parser => {
if ( parser.match ) {
parser.reset();
output = parser.output;
}
} );
return output;
} );
return parsedStr;
}
console.log( parseStr( "onetwothree", {
'one': '1',
'two': '2',
'three': '3'
}) );