PDA

View Full Version : Splitting a variable


MadhatterWales
12-10-2002, 01:49 PM
I'm trying to write a script that will take the input from a formfield and split the result into different variables. E.g.

ABQW123QW12TE1

is split into:

Variable 1: AB
Variable 2: QW
Variable 3: 123
Variable 4: QW
Variable 5: 12
Variable 6: T
Variable 7: E1

But how can I do this in javascript? I've looked through 2 books I have but they don't really seem to cover this - just the basics!

I would really appreciate some help as I'm pulling my hair out! Also can anyone reccomend any good websites for javascript i.e. learning how to use it rather than free scripts!

Thank you

:o

Craig

beetle
12-10-2002, 02:57 PM
Well, it's not very practical to have a separate variable for each value, but you can split that string up into an array.var myStr = "ABQW123QW12TE1";
myStr = myStr.replace(/^(\w{2})(\w{2})(\w{3})(\w{2})(\w{2})(\w)(\w{2})$/,"$1,$2,$3,$4,$5,$6,$7");
var myArray = myStr.split(",");
// myArray == ['AB','QW','123','QW','12','T','E1']There, now you have the array, myArray holding all your values.

Now, the regular expressions that do the bulk of the work here may be over your head, but here (http://www.devarticles.com/art/1/272) is a great beginner's javascript article. Also check out the tutorials at www.w3schools.com and www.javascriptkit.com

Happy coding! :D

chrismiceli
12-10-2002, 03:37 PM
hey beetle, i am just starting reg exp, i get the /w etc, but how do the commas get in the variable?

beetle
12-10-2002, 03:54 PM
Well, whever you surround something in a parenthical in a regex, you create a remembered match, so that it can be used later with what is called a backreference. Consider this simple example that switches every pair of letters in a string around:
var myWord = "word";
myWord = myWord.replace(/(\w)(\w)/g,"$2$1");
// myWord == "owdr";First, the regex matches two word characters. Since each is within it's own parenthical, we have two backreferences, or remembered matches. In the replace portion, we access those backreferences with the dollar sign. The number of the backreference is figured by counting open parentheses, starting from the left. See an example of this in action here (http://www.peterbailey.net/scramble.htm).

So, in my previous example up above, you can see that I insert a comma in the replace string between each backrefrence, which I then use to split the string into an array :D

chrismiceli
12-10-2002, 11:16 PM
i get it, i knew the backreference thing, i just forgot that when you are calling them there is not need for a comma, just like $1$2, i was thinking you had to do it like this %1,%2 etc.
thanx.