JavaScript : Advanced Form Management
Mikael Le Moal
Prohibiting HTML Tags
We proceed differently when it comes to prohibiting HTML tag input. The function
NoHtml() is not used to validate the text value but to directly remove all the HTML tags from it. The function then returns the cleaned
up text.
50: function noHtml(txt) {
51: a = txt.indexOf('<');
52: b = txt.indexOf('>');
53: len = txt.length;
54: c = txt.substring(0, a);
55: if(b == -1) {
56: b = a;
57: }
58: d = txt.substring((b + 1), len);
59: txt = c + d;
60: cont = txt.indexOf('<');
61: if (cont != -1) {
62: txt = noHtml(txt);
63: }
64: return txt;
65: }
As we know that an HTML tag starts with
< and ends with
>, the first step is to obtain the position of the first
< and the first
> (lines 51 to 52). Once we know the positions and the text length, it is then easy to remove the tag. The data on both sides
of the tag is saved in two temporary variables (lines 53 to 58), which are subsequently concatenated to build up the text
again (line 59).
This process can only deal with the first tag. To remove all the tags from the text value, the function needs to be recursive,
i.e. it has to be able to call itself (lines 61 to 63). By the end of the process, all the tags will have been stripped from
the text.