Jump to content

Javascript Replace


Err

Recommended Posts

I have an array with a list of tags I'm not allowing, on a script which directly posts to a webpage. I'm getting all kinds of warnings when I add "<script" to the list of bad tags.Here's a shorten script that I'm working with.

<script type="text/javascript">/* <![CDATA[ */  function valiVal(val) {	var bad = ["<script","<form"];	for (var i = 0; i < bad.length; i++) {	  val = val.replace(bad[i],"");	}	return val;  }/* ]]> */</script>

I'm getting a lot of errors of this sort: The 2 characters "</" have been detected in a wrong place. What's happening is that the browser is reading "<script" in my array and thinking it's the beginning of another script tag, then my browser thinks all the forward slashes on my regular HTML tags are not escaped. I know this is the problem because as soon as I remove "<script" from the array, the errors go away. Is there any possible workaround for this?

Link to comment
Share on other sites

Instead of making a new thread, I'll keep posting in this one.I have another issue. I dropped that way of detecting tags and instead went with regex. Here's what I have so far:

val = val.replace(/<.*?(SCRIPT|FONT|CENTER){1}.*?>/gi,'');

The regex works like this:< - Start tag.*? - Optional range for any characters(SCRIPT|FONT|CENTER){1} - The tag name which should only occur once.*? - Optional range for any characters> - End tagIt works, but not so well. Whenever something like <script> is put at the end of some other tags like <p>, it removes <script> along with everything else. I have no problem if it's before other tags.

Link to comment
Share on other sites

Look at the rules you're telling it:

< - Start tag.*? - Optional range for any characters(SCRIPT|FONT|CENTER){1} - The tag name which should only occur once
In that case, this matches your rules:<div>Here is a script</div>Because "script" comes after a "<" character. I doubt you want to match any "script" which comes after any "<", regardless of what is between them. Instead of matching any character after <, match any character except ">". That means that "script" at least has to show up somewhere in the tag. Although that would still match something like this:<div class="script">If you want to require that the tag name be the first item in the tag, then instead of matching any character, just match any whitespace.
Link to comment
Share on other sites

Updated my code, now it works correctly. Thanks for your help justsomeguy.

[\<][^\>\=]*(script|center|font){1}[^\>]*[\>]

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...