Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string in JavaScript?

Tags:

javascript

I'm just curious how I go about splitting a variable into a few other variables.

For example, say I have the following JavaScript:

var coolVar = '123-abc-itchy-knee'; 

And I wanted to split that into 4 variables, how does one do that?

To wind up with an array where

array[0] == 123 and array[1] == abc 

etc would be cool.

Or (a variable for each part of the string)

var1 == 123   and  var2 == abc  

Could work... either way. How do you split a JavaScript string?

like image 844
willdanceforfun Avatar asked Aug 01 '09 12:08

willdanceforfun


People also ask

What is parsing a string in JavaScript?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

How do I parse a string?

String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.

What is parseHTML in JavaScript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

How do you slice a string in JavaScript?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.


1 Answers

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee'; var partsArray = coolVar.split('-');  // Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc 
like image 157
Amber Avatar answered Oct 14 '22 08:10

Amber