VisualXZ
VisualXZ

Reputation: 213

Replace letters with dashes

Very very junior, apologies if isn't appropriate.

I'm trying to replace all letters in a string with dashes, and my code works if it's only one character, but doesn't with more than one.I've tried a for loop, but doesn't work either. I've been reading other threads, like: Other thread but cannot figure out what I'm doing wrong, and I've been reading for a while now. Could anyone help me out?

This is my code so far:

function replaceLettersWithDashes(str) {
  /* This function will receive a string with a mix of characters. It should return the string with all letters replaced by dashes ('-').

    For example 'You like cake' should return '--- ---- ----', and 'Tree 4, 6, 8' should return '---- 4, 6, 8'.

    */

     return str.replace(/^[a-zA-Z]+$/g , '-');


}

Thanks in advance.

Upvotes: 3

Views: 1821

Answers (5)

Calvin Nunes
Calvin Nunes

Reputation: 6501

use this pattern of regex /[a-z]/gi,
\D means something like “not digit”. It will let you with a very compact code. See snippet below

function replaceLettersWithDashes(str) {
  var newStr = str.replace(/[a-z]/gi, "-");     
 console.log(newStr);
 return newStr;
};

replaceLettersWithDashes("abcdef100abcdi50");

But, if you need just characters (letting white-space and spaces), then go ahead with your regex pattern, just adding the g as said in the comments of your question. :D

Upvotes: 1

nutty88
nutty88

Reputation: 1

return str.replace(/\w/gi , '-')

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386816

You could search for a single letter and replace it with this regular expression, which looks for a letter and replace every letter with a dash. The flags 'g' and 'i' are for global search and case insensitive search.

/[a-z]/gi

If you use a + or * as quantifier, you get all following letters and replace it with a single dash, which is not wanted.

function replaceLettersWithDashes(str) {
    return str.replace(/[a-z]/gi , '-');
}

console.log(replaceLettersWithDashes('You like cake'));
console.log(replaceLettersWithDashes('Tree 4, 6, 8'));

Upvotes: 5

Isaac Villanueva
Isaac Villanueva

Reputation: 274

Here is a quick example !!!

<p id="input"></p>
<p id="demo"></p>

<script>
var str ='asdfdfgfdgdfg';
let res = str.replace(/[A-Za-z]?/g,'-');
document.getElementById("demo").innerHTML = res;
document.getElementById("input").innerHTML = str;
</script>

Upvotes: 1

yajiv
yajiv

Reputation: 2941

Use this regex /[a-zA-Z]/g The reason your code print one dash is because you are replacing the whole word with - . [a-zA-Z]+ means word with letters.

In this regex /[a-zA-Z]/g [a-zA-z] means any one letter and g(global) means search all possible match(not stop on first one)

str='You like cake';
console.log(str.replace(/[a-zA-Z]/g , '-'));

Upvotes: 2

Related Questions