0

I am trying to create a script that will reduce, for example, "Hello. I had a great day today!" to "helloihadagreatdaytoday". So far I have only managed to convert the text to lower case :^)

I have a string of forbidden characters.

var deletthis = ". !";
var a = deletthis.split("");

As you can see, it bans dot, space and exclamation mark, and turns that string into an array. I then give the user a prompt, and run the return string (q) through a for loop, which should delete the banned characters.

for (i=0; i<a.length; i++) {
    q = q.replace(a[i], "");
}

However, this only bans one instance of that character in a string. So if I type "That is nice... Very nice!!!", it would return as "Thatis nice.. Very nice!!".

Any help is appreciated :)!

tufda
  • 27
  • 6
  • This answer should explain nicely: https://stackoverflow.com/a/17606289/769971 – wholevinski Aug 30 '18 at 17:31
  • 3
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – scrappedcola Aug 30 '18 at 17:32

4 Answers4

0

You can use a regular expression for this.

deletthis.replace(/ /g,'')

what this code does is it finds the whitespaces in a string and deletes them,

moreover, a quick google with how to delete spaces in a string would have helped

Shobi
  • 10,374
  • 6
  • 46
  • 82
0

Use a regular expression

a = a.replace(/[\.!]/g, "");

If you don't know the characters beforehand, you can escape them just in case:

a = a.replace(new RegExp("[" + deletethis.split(" ").map(c => "\\" + c).join("") + "]", "g"), "");
riv
  • 6,846
  • 2
  • 34
  • 63
0

Use regex to remove anything that is not alphabet then LowerCase() for case conversion and then split and join to remove any space

let str = "Hello. I had a great day today!"
let k = str.replace(/[^a-zA-Z ]/g, "").toLowerCase().split(" ").join("");
console.log(k)
brk
  • 48,835
  • 10
  • 56
  • 78
0

Using regex could be shorter in this case because it's the same output, so we could use | that means or in a regex:

var str = "Hello. I had a great day today!";

str = str.replace(/\.| |!/g, "").toLocaleLowerCase();

console.log(str)
Emeeus
  • 5,072
  • 2
  • 25
  • 37