How to Replace a JavaScript String

String functions are available in programming languages like JavaScript. These string functions allow manipulation and comparison of strings, including replacement of characters with other characters. Using the "replace" function in JavaScript only takes a few steps.

Instructions

    • 1

      Create the Javascript "script" block tags. Web pages require script tags to use Javascript in the code. The following starts a block of Javascript code:
      <script language="Javascript"></script>

    • 2

      Create the function to replace string text. For this example, a simple find-and-replace is used to demonstrate the replace method.
      <script language="Javascript">
      function ReplaceMyString() {
      {
      </script>

    • 3

      Create a string to replace. The following line of code creates a string that will have replaced characters.
      <script language="Javascript">
      function ReplaceMyString() {
      var replaceme = "Replace here --->.";
      {
      </script>

    • 4

      Define the replacement string. You can replace strings with no characters using "" as the replacement, or you can replace characters with other characters. The following string is the replacement for this example.
      <script language="Javascript">
      function ReplaceMyString() {
      var replaceme = "Replace here --->.";
      var replacementstring = "replaced";
      {
      </script>

    • 5

      Replace the string. The following code replaces string characters using Javascript's replace method.
      <script language="Javascript">
      function ReplaceMyString() {
      var replaceme = "Replace here --->.";
      var replacementstring = "replaced";
      var myNewChars = replaceme.replace("--->.", replacementstring);
      document.write(myNewChars); //writes "Replace here replaced" to the window.
      var myDeletedChars = myNewChars.replace("replaced", ""); //deletes characters
      document.write (myDeletedChars); //writes "Replace here" to the window

      {
      </script>

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured