Powered by Blogger.

Thursday, February 27, 2014

Replace Text in Strings in javascript



Here in this article we will discuss about how we can replace some text in Strings in javascript.

Also check out:

- Encrypt and Decrypt a file in C#.Net

- How to add Eval for hyperlink in gridview in asp.net?

- Get all tables and stored procedures in sql server 2008

The string object provides the replace method for just such purposes.

The following process creates a variable and assigns text to it, replaces that text with
new text, and then displays the results in a browser:

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the body of the document with opening and closing body tags:

<body>
</body>

3. Insert a script block in the body of the document:
<script language="JavaScript">
<!--
// -->
</script>

4. Create a variable named myVariable and assign the value "Hello there" to it:

var myVariable = "Hello there";

5. Create a second variable named newVariable and assign the results of replacing "there" with "Raj" to it:

var newVariable =
myVariable.replace("there","Raj");

6. Display the results of the search and replace so the final page looks like below.

<body>
<script language="JavaScript">
<!--
var myVariable = "Hello there";
var newVariable =
myVariable.replace("there","Raj");
document.write(newVariable);
// -->
</script>
</body>

7. Save the file and close it.

8. Open the file in a browser. You should see the text "Hello Raj" displayed in the browser.