0

So I ran into a problem here. I have an input, and a paragraph that will hold its value.

All nice and good. But, for example, I want to change the letter "a" let's say with "b". On every occurance. How do I do that? I only got to make it work one time on the first occurance like this:

var input = document.querySelector("input");
var h1 = document.querySelector("h1");

input.addEventListener("input", function(){
  h1.innerText = input.value.replace("a", "b");
 
});
<input type="text">
<h1></h1>

How do I make it replace it on every occurance? And how do I make it replace more than one letter? Like, now if the user pressed the letter "b", replace it with "t" for example, besides the first replacement (a with b).

MWR
  • 304
  • 1
  • 2
  • 12
  • 1
    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) – ASDFGerte Aug 26 '18 at 17:14
  • You can pass a RegExp with global flag set to true to replace (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)). That should do it. – FK82 Aug 26 '18 at 17:15

1 Answers1

1

You are adding an event listener to an input with "input" which is invalid. Valid events would be: click, keyup, etc...

Here is a pen that shows how to replace all a's with b's.

It uses a regular expression to find all [a] using /g for global string search and /i for case-insensitive and replacing them with "b". find: /[a]/gi replace: "b"

var input = document.querySelector("input");
var h1 = document.querySelector("h1");

input.addEventListener("keyup", function() {
  h1.innerText = input.value.replace(/[a]/gi, "b");
});

https://codepen.io/jthomas077/pen/mGPbrB

Jawsh
  • 31
  • 3
  • Sorry but "input" is an actual event listener. https://www.w3schools.com/jsref/event_oninput.asp And I was just about to type "oh, I missed the '/gi' ". I'm really not that great at regex! Thanks for helping. – MWR Aug 26 '18 at 17:19
  • Interesting... never used "input" as an event lol. RegEx's can be mind-numbing lol. This is a great regex tester/builder to play with: https://regex101.com/. No worries man! – Jawsh Aug 26 '18 at 17:23
  • Actually there's a problem. So, I successfully replaced "a" with "b". But then if I want to replace "b" with "c" I will always get "c" even if I press "a". – MWR Aug 26 '18 at 17:28
  • What exactly are you trying to accomplish with your replacement logic? – Jawsh Aug 26 '18 at 17:56
  • I'm trying to make a "translator" to a language that I've invented. And a is going to be replaced with e, e with i, i with o etc, like, "person" would be "pirsun". – MWR Aug 26 '18 at 18:05