1

I have a text field in which the user inputs some text. I'd like to take the first word of that text and turn it into a global variable name for an object holding the rest of the string content. More string content will be added to object later, so internal indexing inside the object is required.

var textInput = $('#inputText').val();
var splitString = textInput.split(" ");
var firstWord = splitString[0];

This is where I get stuck. How please do I create a new object with the string referenced by firstWord as the object's reference?

Many thanks in advance.

4
  • You could either use Eval(...) or window["objectName"] = Commented Aug 7, 2013 at 11:42
  • An object doesn't have a name... Do you mean that you want to create a variable with that name, containing a reference to an object? Would it be a local or global variable? Commented Aug 7, 2013 at 11:42
  • Yes, that is what I mean't Guffa. I understand that eval is bad practice Serge? Commented Aug 7, 2013 at 11:44
  • eval is almost evil :) In the sense you should validate user input to prevent code injection… in your case It seems you just need to grab the first token of a string, operation that could be done quite safely… but… if you mean to pollute the global scope (i.e. windows) than… It should definitively a bad idea. Commented Aug 7, 2013 at 11:55

1 Answer 1

2

I would try something like this:

globalUserObjects = {};

var textInput = $('#inputText').val();
var splitString = textInput.split(" ");
var firstWord = splitString[0];

globalUserObjects[firstWord] = {};

// Now later you can add stuff to it

globalUserObjects[firstWord]["firstName"] = "John";
globalUserObjects[firstWord]["lastName"] = "Smith";
Sign up to request clarification or add additional context in comments.

2 Comments

You are right of course. Thank you very much. I couldn't see the wood for the trees.
No problem. Let me know if you have any followup questions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.