javascripthtmlregexreplace

JavaScript replace and regexp syntax issue


I was trying to replace more than one string in an exercise but I'm stuck with a regexp. Since it's impossible to call two times replace I need to write a regexp to achieve my goal and I'm a beginner with regexps.

Basically I would like to write trace("Hello World"); and replace / remove trace("at start and ");" at the end of my String.

If I could use replace two times in a function it could be written as the following statement:

<input type="text" id="input" onKeyUp="update()">
<p id="output"></p>

The script could be look like this:

    function update(){
            var x = document.getElementById("input").value;
            if (x.startsWith("trace(\"") && x.endsWith("\");")){
                document.getElementById("output").innerHTML = x.replace('trace(\"', '');
                document.getElementById("output").innerHTML = x.replace('\");', '');
            }else{
                document.getElementById("output").innerHTML = "";
            }
        }

So till now my output is trace("Hello World or Hello World");if I comment the second replace statement.

The output should be Hello World with a correct regexp, I suppose.


Solution

  • I hope the below answer is suitable for you.

    x=x.replace('trace("', '');

       function update(){
                var x = document.getElementById("input").value;
                if (x.startsWith("trace(\"") && x.endsWith("\");")){
                  x=x.replace('trace(\"', '');
                    document.getElementById("output").innerHTML = x.replace('\");', '');
                }else{
                    document.getElementById("output").innerHTML = "";
                }
            }
    <input type="text" id="input" onKeyUp="update()">
    <p id="output"></p>

    Thank you.