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

Viewed 130

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 ?

3 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"));

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'
 }) );

Related