Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring out of a string using Javascript

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.

like image 382
Jake Avatar asked Apr 27 '11 20:04

Jake


People also ask

How can you extract a substring from a given string?

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.

How do you slice a substring 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.

What substring () and substr () will do?

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 .

How do you find out the part of the string from a string?

To locate a substring in a string, use the indexOf() method.


2 Answers

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];
}
like image 198
Neil Avatar answered Nov 02 '22 17:11

Neil


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];
});
like image 2
Karl Laurentius Roos Avatar answered Nov 02 '22 17:11

Karl Laurentius Roos