Reputation: 6768
i have a condition where i have to replace the empty space with '-' and all other symbols like " *,%,',@,$ ....etc" should be removed , so for instance if i have a word real life , it should be written as real-life , another example , if i have a words fire officer's association it should be written as fire-officers-association .
I can replace empty space using jquery like :
var product= $("#product").val().replace(/ /g,'-');
but i m struggling to remove the special characters
Can any provide any suggestion or advice on how to acheive that Thanks
Upvotes: 2
Views: 19351
Reputation: 33870
Add this to your code :
//@Author Karl-André Gagnon
if(String.prototype.replace){
String.prototype.oldReplace = String.prototype.replace;
String.prototype.replace = function(find, replace){
var stringReturned = this;
if(!find || !replace) return undefined;
if(find instanceof Array){
if(typeof replace == 'string'){
for(var i = 0; i < find.length; i++){
stringReturned = stringReturned.oldReplace(find[i],replace);
}
}else if(replace instanceof Array && replace.length == 1){
for(var i = 0; i < find.length; i++){
stringReturned = stringReturned.oldReplace(find[i],replace[0]);
}
}else if(replace instanceof Array){
for(var i = 0; i < find.length; i++){
stringReturned = stringReturned.oldReplace(find[i],replace[i] ? replace[i] : '');
}
}else{
stringReturned = undefined;
}
}else{
stringReturned = stringReturned.oldReplace(find,replace);
}
return stringReturned;
}
}
This will allow you to pass array as argument for .replace()
.
Then you can do this :
string.replace([/ /g, /["*%'@$]/g],['-', ''])
basicly, the first cell of the first array will be replaced by the first cell of the second array (like the replace in php).
Fiddle : http://jsfiddle.net/6sk3n/
Upvotes: 2
Reputation: 1286
Try using:
var product= $("#product").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, ' ')
Fiddle: http://jsfiddle.net/4YwNC/
Upvotes: 1