0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It works! I tough that I needed a regex to reach my goal. If someone have an idea to realize this with a regex, feel free to answer just to satisfy my curiosity. ;)
Your answer is short, clear and efficient logesh sankar!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.