Im creating an ID from elements name
attribute and they have some not allowed characters, I would like to create a function that replaces charcters if they are not on the list with _
. I tried to google it, but all I found was regexp examples with where not quite what Im looking for.
This is what I made:
/([^A-Za-z0-9[\]{}_-])\s?/g
but this doesn't exclude ]
and [
, maybe some other characters too.
How can I make that it replaces all characters with _
that are not [A-Za-z0-9]
, -
, _
, .
, :
?
EDITED
.. and if first character is not a number make it one.
If somebody knows a better way how to do it, please share it.
Have you tried just the Not word character (i.e. \W
) matches everything that is not A-Za-z0-9_ (which also means a space)
so
/\W/g
in javascript something like
var id = "What ever your id is [] {} - &";
var cleanedId = id.replace(/\W/g,'_'); //cleanedId is "What_ever_your_id_is__________"
Assuming your replacing them all with an underscore of course
Example regex here
You should use the replace() function as following:
var temp = "some id to validate";
var i = "";
if(!$.isNumeric(temp[0])){
i = parseInt(Math.random()*10);
}
temp = i+temp.replace(/([^A-Za-z0-9[\]{}_.:-])\s?/g, '');
//here the id is a valid id
See jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With