Hezerac Hezerac - 3 months ago 7
Javascript Question

How to extract expected value from string, html input submission

Is there a way to extract an expected value from a string within an html input submission?

If the following is a single submission, and its parts delimited by double quotes here only for clarity, is there a way to set the expected value, as well as the trailing string, to variables?:


"expected-value" "second part of same input string, the quotes arent real"

ex.

var exp = "expected-value";

var trail = "second part of same input string, the quotes arent real";

Upon input submission how to parse string and extract each and to their variables?

Answer

Use Javascripts split method and a proper delimiter and you can 'split' the string into an array, and then access the different parts of the array.

I would avoid the double quotes. You'll have to figure out how and where your delimiter is, but split is pretty flexible in those regards.

$text = "expected-value|second part of same input string, the quotes arent real";
result = $text.split('|');

var exp = result[0];
var trail = result[1];

console.log(exp);
console.log(trail);
// output:
// expected-value
// second part of same input string, the quotes arent real

To get the value from a text input you would use something like:

document.getElementById('textbox_id').value

Split method documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split