method to convert form names to valid JavaScript names?
i am processing an object in JavaScript that has been returned from an API that may contain variable names that are not valid JavaScript variable names. (these names are valid in the naming convention of the syste开发者_运维技巧m of the API i am using)
in one case, the name starts with a number, e.g. '5story'
what is the best way to convert this name to a valid JavaScript variable name?
(i am familiar with the form of legal JavaScript names. a useful answer to this question would be a (hopefully simple) algorithm e.g. prefix a $ to the name and then strip it when returning the form to the API)
(i note that it would be preferable if the JavaScript API did not create invalid names)
Note that I'm not sure if you're asking about html identifier names (you mention "form") or Javascript variable identifiers, but how about stripping any character that is not a word character (A-Z
, a-z
, 0-9
, _
) and prepending with an underscore?
var v = ' .-*&*$*$W 5 foo Bar';
v = '_' + v.replace(/\W/g, '');
v; // _W5fooBar
The .replace()
will strip characters that are not legal in variable identifiers.
You could prepend with the $
symbol instead of underscore for a legal variable name too.
You could creat a wrapper object that also contained a back reference to the original name.
function MyApiClient()
{
var _self = this;
this.RegisterWrapper = function(strName, objValue, explicitName)
{
var newName = (explicitName != null) ? explicitName : '_' + strName.replace(/\W/g, '');
_self[newName] = {ApiName : strName, Value : objValue};
return _self[newName];
}
}
//implementation
var client = new MyApiClient();
client.RegisterWrapper('5story', [0,1,2,3,4,5]);
console.log(client._5story.Value); //output: Array() [0,1,2,3,4,5];
//or
var o = client.RegisterWrapper('5story', {a:'b'}, '_myName');
console.log(o.Value); //outpus Object a: 'b'
console.log(client._myName.Value); //outpus Object a: 'b'
This extends a couple additional benefits
- Scope: when creating the new objects they will be encapsulated and not globals
- Reference: if you have reference to this object - you can use it to hit your API (because it will contain the old name)
- Flexibility: you can either register the wrappers dynamically through a loop as you parse a string returned from the api or explicitely like above.
Do you have any more information about the actual api?
精彩评论