简体   繁体   中英

Javascript/Jquery Regex Split

In Javascript, I am getting a string like I have a string exactly like H01=13 H02=12 H03=43 H04=56..... ?

I want to split the string and give it to the different textboxes in the page like

txtHeight01's value(text) is 13 
txtHeight02's value(text) is 12 
txtHeight03's value(text) is 43 

Part of the code would be like

paddedcounter = i.padLeft(2, '0'); //(i is for(i=0;i<3;i++)
$('#txtHeight' + paddedcounter).val()=//These will the values from the splitted string.
    var strTest = 'H01=13 H02=12 H03=43 H04=56';
    var splitArrayBySpace = strTest.split(' ');
    for(var i = 0; i < splitArrayBySpace.length; i++){
            var splitArraybyValue = splitArrayBySpace[i].split('=');
            $('#txtHeight' + splitArraybyValue[0]).val(splitArraybyValue[1]);
    }        

This should do it.

You don't have to use regex, you can do something like this :

$(document).ready(function() {
    var string = 'H01=13 H02=12 H03=43 H04=56';
    var split = string.split(' ');

    for (var i = 0, length = split.length; i < length; i++) {
        split[i] = split[i].split('=');

        //Then you can do:
        $('#txtHeight' + i).val(split[i][1]);
    }

    console.log(split);
});

which give you this :

[["H01", "13"], ["H02", "12"], ["H03", "43"], ["H04", "56"]]

generate a key value object:

var arr = 'H01=13 H02=12 H03=43 H04=56'.split(' '),
    obj = {};

for (var i = 0; i < arr.length; i++) {
    var val = arr[i].split('=');
    obj[val[0]] = val[1];
}

console.log(obj);
/* output Object
{
    H01: "13",
    H02: "12",
    H03: "43",
    H04: "56"
}
*/

than u can create string of your choice:

var text = [];
for (var j in obj) {
    var num = j.replace('H',''),
        value = obj[j];                        

    text.push('txtHeight' +j + '\'s value(text) is ' + value);
}
console.log(text.join('<br />'));
// output text
txtHeightH01's value(text) is 13<br />
txtHeightH02's value(text) is 12<br />
txtHeightH03's value(text) is 43<br />
txtHeightH04's value(text) is 56

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM