Pasha
Pasha

Reputation: 181

How to replace a string using JS?

Somewhere in the html file I have the following lines :

/*my lines*/ $(function(){i=1;}); /**********/

I need to dynamically replace this lines using js with this

/*my lines*/ $(function(){i=2;}); /**********/  

This is what I tried

var outerHTML = document.documentElement.outerHTML;
outerHTML = outerHTML.replace("/*my lines*/","/*my lines*/$(function(){i=2;});"); 

But my regex is not correct. How can I replace it ? How to locate the substring that starts with /*my lines*/ and ends with /**********/ ?

Upvotes: 0

Views: 676

Answers (4)

Thealon
Thealon

Reputation: 1945

This will provide your answer:

Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.

However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.

After you have that set up you can now manipulate the text of an element. To start off, let's try changing the text inside a bold tag.

Example:

<script type="text/javascript">
function changeText(){
    document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p> 
<input type='button' onclick='changeText()' value='Change Text'/>

However, this is with user interaction, you could change it so that this function will be called in another function wich will trigger this.

Upvotes: 2

Guffa
Guffa

Reputation: 700472

That's not a regular expression at all, that's a string. The replace method doesn't try to turn the string into a regular expression, it will just replace the first occurance of the string.

You need to escape the * characters in the regular expression, and the / characters if you use a regular expression literal:

outerHTML = outerHTML.replace(/(\/\*my lines\*\/)[^\/]+(\/\*+\/)/g,"$1 $(function(){i=2;}); $2");

Upvotes: 1

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Don't use quote to declare regex. Because in your code, javascript think that you use a string instead of a regex.

outerHTML.replace(/\/\*my lines\*\//g,"/*my lines*/$(function(){i=2;});"); 

Upvotes: 3

Samir Das
Samir Das

Reputation: 1908

Try this

console.log(str.replace(/\/\*my lines\*\/.*\/\*\*\*\*\*\*\*\*\*\*\//,"/*my lines*/$(function(){i=2;});"));

Upvotes: 2

Related Questions