Extract substring from string using javascript

All,

I have the following html as a string in javascript. I need to extract a string into "value", broken by the specified divider "|" and put two variables.

var html = '<div><input name="radBtn" class="radClass" style="margin:auto;" 
       onclick="doSomething();"
       value="Apples|4567" type="radio">
</div>';

The required output is two variables with the following values:

fruitName = Apples
fruitNumber = 4567

Note: there may be many radio buttons with the same name.

+5
source share
6 answers

If you can assume that your HTML will always be simple (i.e. just one value attribute and nothing more than a value attribute), you can do something like this:

var fruit = html.match(/value="(.*?)\|(.*?)"/);
if (fruit) {
    fruitName = fruit[1];
    fruitValue = fruit[2];
}
+8
source

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];
});
+1
source
var div = document.createElement("div");
div.innerHTML = '<input name="radBtn" class="radClass" style="margin:auto;" onclick="doSomething();" value="Apples|4567" type="radio"></div>';  

var str = div.getElementsByTagName("input")[0].split("|");

var fruitName = str[0];
var fruitNumber = str[1];

/*
Now,
fruitName = "Apples"
and
fruitNumber = 4567
*/
+1
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

. javascript?

0
$(function() {
    $("INPUT[name=radBtn]").click(function() {
        var value = $(this).val().split("|");
        var fruitName = value[0];
        var fruitNumber = value[1];

        // Add to an array, ajax post etc. whatever you want to do with the data here
    });
});
0

:

var fruit = (function() {
    var fruits = $(html).find('.radClass').val().split('|');
    return {
        fruitName: fruits[0],
        fruitNumber: fruits[1]
    };
}());

You will receive the following object:

fruit.fruitName // Apples
fruit.fruitNumber // 4567
0
source

All Articles