4

I have an arbitrary string that comes from a database. I want to place this string as an HTML class name on a web page. I am not sure what characters to expect. How can I remove the spaces and special characters to make it "safe" to be a CSS class name?

After some research, it seems space and these characters need to be remove:

!"#$%&'()*+,./:;<=>?@[\]^`{|}~

What is the best way to remove them?

TruMan1
  • 27,054
  • 46
  • 150
  • 273

2 Answers2

5

You might want to look at this thread to get a better understanding of valid CSS names.

I recommended a utility function as below, you should test/change the regex expression as needed.

Regex re = new Regex(@"[!""#$%&'()\*\+,\./:;<=>\?@\[\\\]^`{\|}~ ]");
string outputString = re.Replace(inputString, string.Empty); 
Community
  • 1
  • 1
Channs
  • 2,031
  • 1
  • 14
  • 18
  • This does not seem to remove spaces, how can this be adjusted? – TruMan1 Jun 07 '12 at 19:29
  • @TruMan1 - Updated my original answer with the correct regex syntax. Had to escape the special characters ([reference](http://www.regular-expressions.info/characters.html)). Hope this helps. – Channs Jun 07 '12 at 19:44
  • For reference, in case someone might find it useful, here's the same regex approach in JavaScript, modified to insert a dash for each subsequence of forbidden characters: var outputString = inputString.replace(/[!"#$%&'()\\*\+,\./:;<=>\?@\\[\\\\]^`{\|}~ ]+/g, '-'); – Kjell Rilbe Dec 02 '14 at 15:12
0

You are try System.IO.Path.GetInvalidFileNameChars to filter out special characters:

var tagName = "fo@3do@11~1298#bar";
    var invalidChars = System.IO.Path.GetInvalidFileNameChars();
    var cleanTagName = new string(tagName.Where(m => !invalidChars.Contains(m)).ToArray<char>());
Firoz Ansari
  • 2,407
  • 1
  • 20
  • 36
  • Invalid filename characters and invalid CSS class name characters are not equivalent sets. For example, `+` is allowed in filenames, but not CSS class names. – Cody Oct 28 '13 at 20:58