Question

I want to convert text strings to numerical values using Javascript in order to create custom variables for a survey link. For example, I have the following possible values for the variable Q14:

Inland Great Lakes Rivers Coastal N/A

How can I convert these text values into numerical valuesso that Inland=1, Great Lakes=2, Rivers=3, Coastal=4, N/A=5?

Was it helpful?

Solution

If you store those values in an array, then you can use indexOf to find the match:

function getLocationNumber(location) {
    var locationOptions = ["Inland", "Great Lakes", "Rivers", "Coastal", "N/A"];
    var locationNumber = locationOptions.indexOf(location) + 1;
    return locationNumber;
}

// Example:
getLocationNumber("Great Lakes") // returns 2
getLocationNumber("Coastal") // returns 3

OTHER TIPS

If you're looking for a C++ solution, here's a similar question and solution: splitting string into array. After you've split it into an array you can use the array index + 1 for the value you're looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top