user15054235
user15054235

Reputation:

Codewars: how can i solve this codewar question?

I have attempted this so many times even using regex and the len, left, mid and right methods and i cant seem to get it right. The goal is this aaa33aa4a7a6 ==> aaa33aa-a-a-

Upvotes: 0

Views: 743

Answers (3)

Maik Lowrey
Maik Lowrey

Reputation: 17594

I convert the string to an array the reverse it. Afterwards i iterate this new array and create a new array by condition (count the matches of numbers).

const str = `abc12aa3b9c8`
let arr = str.split("").reverse(); 

let counter = 0;
let newStr = []

arr.forEach(e => {  
  if (isNaN(e)) {       
    newStr.push(e)
  } else {    
    newStr.push(counter < 2 ? '-' : e)         
    counter++;
  }
})


console.log('res',newStr.reverse().join(""))

Upvotes: 0

Jared
Jared

Reputation: 1374

Split your string to array, reverse, replace what you need, reverse it back, join into a result string:

    var str = 'abc12aa3b9c8';
    var counter = 3;
    str = str
      .split('')
      .reverse()
      .map(function(char){
        if( !isNaN( char ) && counter-- > 0 )
          return '-';
        return char
      })
      .reverse()
      .join('');
    console.log( str );

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386766

You could check if there comes at least two or less digits in the string and replace the digits.

const
    regex = /\d(?=(\D*\d){0,2}\D*$)/g;

console.log('abc12aa3b9c8');
console.log('abc12aa3b9c8'.replace(regex, '-'));

console.log('abc12aa3b9c8x');
console.log('abc12aa3b9c8x'.replace(regex, '-'));

Upvotes: 2

Related Questions