normalizeFilename

Remove unwanted chars from a given value

by web-nfo.com

HTML

<div id="output"></div>

CSS

body {
  font-family: 'courier new';
}

JavaScript

/**
 * normalizeFilename(value)
 * Remove unwanted chars from a given value
 */
function normalizeFilename(value)
{
	// Allow only specific characters, replace others with sign char (-)
	value = value.replace(/[^A-Za-z-_\.0-9]/g, '-');
  
  // Convert multiple separators into one separator
  value = value.replace(/-+/g, '-');
  
  // Convert to lowerstring
  value = value.toLowerCase();
  
  // Replace beginning separator char
  value = value.replace(/\-$/, '');
  
  // Replace last separator char
  value = value.replace(/^\-/, '');

	// Do not allow an empty value
	if(value.length === 0) {
  	value = '-';
  }

  return value;
}


/**
 * Testing
 */
values = [
	'',
	'TeSt',
  'test.zip',
  'test.pdf',
  'This is my "_,_FILENAME_,_" (testing).... etc... ~ something.zip',
  '-------oke-----.zip------',
  '$oMeTh!nG_w1Th-$pe€ial-CH^rs.zip',
	'test0258.test,another523=~oke.zip',
];

for(var i=0; i<values.length; i++) {
	var value = values[i];

	var element = document.createElement("p");
	element.innerHTML = value;
  element.innerHTML += '<br>';
  element.innerHTML += normalizeFilename(value);
  
  document.getElementById('output').appendChild(element);
}