1

I am trying to replace the javascript code in html by javascript

So I am testing like this.

var test = new String("<script type=\"text/javascript\"> test </script>");

test.replace(/<script type=\"text\/javascript\">.+<\/script>/g,"");
//this doesn't match

console.log(test.toString());

test.replace doesn't match and console.log shows this.(nothing happens!)

<script type="text/javascript"> test </script>

Is there any mistake??

14
  • 5
    .replace returns a new string. But the more important question is, why are doing this? What problem are you trying to solve here? Commented Feb 16, 2014 at 22:46
  • 1
    An aside not an answer, but you don't need new String() or .toString() there - every string in JS is an object of type string. Commented Feb 16, 2014 at 22:46
  • 1
    I'd be curious to know why you need to do this. Commented Feb 16, 2014 at 22:47
  • 1
    @IMSoP: Well, not quite. Most are string primitives. Using new String is a terribly bad idea. Anyways, whitebear: why’re you trying to do this? It doesn’t seem like a good idea somehow. Commented Feb 16, 2014 at 22:47
  • 2
    @IMSoP: Technically no. There are string primitives and string objects and they behave slightly differently. You should never use new String thought, because it makes things very confusing. Commented Feb 16, 2014 at 22:47

1 Answer 1

2

test.replace returns the replaced string, it does not replace test in place.

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

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

Comments

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.