Jump to content

[SOLVED] Use Javascript to replace/strip out character


Jason28

Recommended Posts

Hello, I would like to use javascript to locate two asterisks side by side ** and replace them with only one asterisk before submitting the form. So if someone enters "blah**" or "**blah" or just "**" it will remove one of those asterisks.  Here are my current form fields:

 

<input name="search_user" id="search_user" type="text" size="45" maxlength="25" value="{search_user}">
<input name="search_musician" id="search_musician" type="text" size="45" maxlength="100" value="{search_musician}">
<input name="search_song" id="search_song" type="text" size="45" maxlength="255" value="{search_song}">

 

If you could provide a working example of javascript to replace ** with * that would be really great :)  Thanks!

You don't state what should happen if there are three or more asterisks in a row!

 

I will assume that any multiple succession of asterisks (2 or more) should be replaced with a single asterisk. Here's a sample script:

 

<html>
  <head>
    <script type="text/javascript">
      function removeAst(fieldObj)
      {
          fieldObj.value = fieldObj.value.replace(/\*{2,}/g, '*');
      }
    </script>
  </head>

  <body>
      Enter a value and tab out:<br>
      <input type="text" name="theField" onchange="removeAst(this);" />
  </body>
</html>

Haha works great thanks a lot :)  I am a php guy I do not know how you guys know javascript it seems more difficult.  I tried reading a book on it but it must have sucked since I still haven't learned how to create custom codes like the one you have provided.

Personally I think JavaScript and PHP are VERY similar.

 

The function simply accepts a form field object. The function then replaces the value of that form field with the same value run through a bit of RegEx code. A PHP implementation would look similar:

 

(not tested)

$cleanValue = preg_replace('(/\*{2,}/', '*', $_POST['fieldname']);

'

In fact, it is fine to have this functionality in JavaScript, but you should really be doing it on the server-side (i.e. in PHP) as users may have JavaScript disabled.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.