Basta020
Basta020

Reputation: 3

How to remove the (.) in a string and then display every alphabetic character with a dot

I would like to have a a function who takes a string a parameter, removes the dots, loops trough every alphabetic character and display like this (A.B.C.) when input is (A..B..C) for example.

How can I build this function?

Here for I have the next function in mind, unfortunately is not working I get a output result like this (hfff) when input string is "h..f.ff", would like to have this output (H.F.F.F)


function filter (initials) {
  let result = initials.replace(/\./g, '')
  let i;
  for (i = 0; i < result.length; i++) {
     result[i] + ".";
  }
  return result
  console.log(result)
}
const initials = "h..f.ff"
console.log(filter(initials)) 

Upvotes: 0

Views: 56

Answers (4)

blex
blex

Reputation: 25634

You could use split, map and join

function filter(initials) {
  return initials.replace(/[^a-z]/gi, '') // Remove non-letters
                 .toUpperCase()
                 .split('')              // Convert to an Array
                 .map(l => l + '.')      // Add dots
                 .join('');              // Join 
}

const initials = "h..f.ff";
console.log(filter(initials));

Upvotes: 2

StarshipladDev
StarshipladDev

Reputation: 1145

Use replaceAll to remove all . char with nothing.

Then from that string, make all letters uppercase.

From that string, split the whole word up into and array of letters using split (Each piece of the string on each side of the parameter passed to split gets turned into an element in a new array. if you leave the parameter blank, it's just each character in the string)

Finally join each those elements together with a . between them using join

function filter (initials) {
   initials=initials.replaceAll('.','');
   initials=initials.toUpperCase();
   initials=initials.split('');
   initials=initials.join('.');
   return initials;
 }

var test = "h..f..t....e.Z";
console.log(filter(test));

Thanks @blex for the snippet advice

Upvotes: 0

Alberto
Alberto

Reputation: 12939

well you can:

  1. make the string uppercase
  2. split the string char-by-char
  3. filter only letters
  4. join using "."
function format(string){
    return string.toUpperCase()
             .split("")
             .filter(c => /[a-zA-Z]/.test(c))
             .join(".")
 
}
format("h..f.ff") // "H.F.F.F"

Upvotes: 0

digitalniweb
digitalniweb

Reputation: 1142

You need to assign this

result[i] + ".";

to something. Do:

let i,newresult;
for (i = 0; i < result.length; i++) {
  newresult += result[i] + ".";
}

Upvotes: 0

Related Questions