Go to GoReading for breaking news, videos, and the latest top stories in world news, business, politics, health and pop culture.

How to Use JavaScript to Remove Dashes

104 16
    • 1). Launch Notepad and open one of your HTML files.

    • 2). Add the following code to the document's "body" section:

      <input type="text" />

      <input type="button" value="Convert Dashes to Blanks" onclick="return ConvertToBlanks()" />

      <input type="button" value="Remove Dashes" onclick="return RemoveDashes()" />

      This creates a text box and two buttons. When clicked, the "Convert Dashes to Blanks" button calls a JavaScript function named "ConvertToBlanks" that removes converts dashes to blanks in a text string. The "Remove Dashes" button calls the JavaScript function named "Remove Dashes." This function removes dashes and leaves no spaces in the text. This is useful when you need to convert a string such as "123-456" to "123456," instead of converting it to "123 456."

    • 3). Add this code to the document's "head" section:

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

      function ConvertToBlanks() {

      var dash = "-";

      var textBoxObject = document.getElementById("Textbox1");

      var textString = textBoxObject.value;

      var newTextString = textString.replace(/-/gi," ");

      alert("New Text = " + newTextString);

      }

      function RemoveDashes() {

      var textBoxObject = document.getElementById("Textbox1");

      var textString = textBoxObject.value;

      var newTextString = textString.replace(/-/gi, "");

      alert("New Text = " + newTextString);

      }

      </script>

      The "ConvertToBlanks" function retrieves the text from the text box and stores it in the variable named "textString." The function then executes the "replace" method as shown in this statement:

      var newTextString = textString.replace(/-/gi, " ");

      The "replace" method takes two parameters. The first parameter, between the slashes, is the character you want to replace. The second parameter defines the replacement character. In this example, the character to replace is the dash. The replacement character is a blank. The "RemoveDashes" function is similar to the "ConvertToBlanks" function. Note, however, how its "replace" method differs. The replacement character in the "RemoveDashes" function is "". This creates a null character and converts values such as "123-456" to "123456" by stripping away the dash and leaving no space in place of the dash.

    • 4). Save the HTML file, and open it in your browser. Enter "123-456-78" in the text box and click "ConvertToBlanks." A message box displays the converted text, "123 456 78." Click the "Remove Dashes" button. The message box displays "12345678."

Source...

Leave A Reply

Your email address will not be published.