开发者

Extract substring out of a string using Javascript

开发者 https://www.devze.com 2023-03-01 16:40 出处:网络
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.

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 = '<d开发者_如何学Goiv><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.


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];
});


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
*/


Here's one way:

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

You'll get an object like this:

fruit.fruitName // Apples
fruit.fruitNumber // 4567


var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

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

see: How to parse a string in javascript?


$(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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号