Showing posts with label Regex. Show all posts
Showing posts with label Regex. Show all posts

Sunday, January 1, 2012

Javascript Regular Expression to match a comma delimited list

This method uses the JavaScript String's match() method to parse a comma delimited list and show its content in a Panel control.

You can try it here http://jsfiddle.net/38tXU/
function parseList(list) {
    var reg = list.match(/\w+(,\w+)*/g);
    document.getElementById('pnl').innerHTML = 'Total length:' + reg.length + '<br />';
    for (var i = 0; i < reg.length; i++) {
        document.getElementById('pnl').innerHTML += 'Token:\'' + reg[i] + '\'<br />';
    }
}
//Call parseList function
parseList('item1, item2, item3');

Monday, February 1, 2010

How to remove HTML Tags from string in C#

I will show you three different methods to remove HTML tags from string in C#:

1. By using Regex:
public static string RemoveHTMLTags(string html)
{
 return Regex.Replace(html, "<.*?>", string.Empty);
}

2. By using Compiled Regex for better performance:
static Regex htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
   
public static string RemoveHTMLTagsCompiled(string html)
{
 return htmlRegex.Replace(html, string.Empty);
}

3. By using Char Array for faster performance for several HTML files:
public static string RemoveHTMLTagsCharArray(string html)
{
 char[] charArray = new char[html.Length];
 int index = 0;
 bool isInside = false;
  
 for (int i = 0; i < html.Length; i++)
  {
   char left = html[i];

   if (left == '<')
    {
     isInside = true;
      continue;
    }

   if (left == '>')
    {
     isInside = false;
     continue;
    }

   if (!isInside)
    {
     charArray[index] = left;
     index++;
    }
   }

 return new string(charArray, 0, index);
}