All,
I have the following html as a string in javascript. I need to extract the string in "value", split by the specified delimeter "|" and put in two variables.
var html = '<div><input name="radBtn" class="radClass" style="margin:auto;"
onclick="doSomething();"
value="Apples|4567" type="radio">
</div>';
Required output is two variables having the following values:
fruitName = Apples
fruitNumber = 4567
Note: There can be many radio buttons with the same name.
You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.
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.
The difference between substring() and substr()substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 . Negative lengths in substr() are treated as zero, while substring() will swap the two indexes if end is less than start .
To locate a substring in a string, use the indexOf() method.
If you can assume that your HTML is always going to be simple (i.e. only one value attribute, and nothing else that looks like a value attribute), then you can do something like this:
var fruit = html.match(/value="(.*?)\|(.*?)"/);
if (fruit) {
fruitName = fruit[1];
fruitValue = fruit[2];
}
Here's how you can do it:
$("input[name='radBtn']").click(function(){
var val = $(this).val();
val = val.split("|");
var fruit = val[0];
var number = val[1];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With