Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to create a valid id from string. Regular Expression

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.

like image 224
Cirvis Avatar asked Aug 14 '14 21:08

Cirvis


2 Answers

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

like image 194
OJay Avatar answered Oct 17 '22 16:10

OJay


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

like image 3
Eiiki Avatar answered Oct 17 '22 15:10

Eiiki