0

I am a total noob to javascript and need some direction.

I am trying to do the following:

Create 3 text boxes:

  • User enters a string in the first text box.
  • User enters string to be replaced (part of the first string) in the second text box.
  • User enters new string to insert in third text box.

Button – calls a function to perform the replacement and displays the results in all uppercase.

I am using document.querySelector("myID").value; to grab the value entered, but i am not sure if i should be using replace() for this. Or if the variable needs to be converted to something else. (very confused)

If anyone could point me in the right direction it would be much appreciated.

Syakur Rahman
  • 2,056
  • 32
  • 40
Wil
  • 49
  • 1
  • 7

2 Answers2

1

You could use something like this:

<body>
    <textarea id="textArea" ></textarea><br>
    <input id="input1" /><br>
    <input id="input2" /><br>
    <input type="button" value="Replace" onclick="doReplace()" />
    <div id="output">OUTPUT!</div>

    <script>
        function doReplace() {
            var getById = document.getElementById.bind(document);
            var get = function(id) { return getById(id).value };
            var text = get('textArea'),
                input1 = get('input1'),
                input2 = get('input2'),
                div = getById('output');

            var regex = new RegExp(input1, "g"); // to replace globally you need this!
            div.innerHTML = text.replace(regex, input2).toUpperCase();
        }
    </script>
</body>

EDIT:

jsfiddle.net

msynk
  • 21
  • 4
0

Javascript by default recognizes everything as string, when given a string operation. In this case you could use replace() method directly without any conversions.

Syakur Rahman
  • 2,056
  • 32
  • 40