Home > Software engineering >  Javascript replace and regexp syntax issue
Javascript replace and regexp syntax issue

Time:10-31

Hello everybody I was trying to replace more than one string in an exercise for myself but I'm stucking 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 noob with Regexp.

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 write as 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.

Any help will be appreciate! And sorry for my poor English. Best regards. Nicolas.

CodePudding user response:

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.

  • Related