Reputation: 1955
I have a string as below
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode="abc"><c>string content</c></b></a>"
Then I split it with &
var b = a.split('&');
Then further more I split b with = in loop and append to the form
$.each(b, function (index) {
var paramsV = b[index].split('=');
frm.append('<input type="hidden" name="' + paramsV[0] + '" value="' + paramsV[1] + '" /> ');
});
But when it split with = that time it is splitting result string which have = inside the string and it is splitting that too. I would like to know how I can stop splitting the result string.
Upvotes: 0
Views: 351
Reputation: 536
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode='abc'><c>string content</c></b></a>";
var b = a.split('&');
$.each(b, function (index) {
var index1 = b[index].indexOf("=")
var markup ='<input type="hidden" name="' + b[index].substring(0, index1) + '" value="' + b[index].substring(index1) + '" /> ';
console.log(markup);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Check it
Upvotes: 0
Reputation: 3530
You have made a mistake in variable declaration. Inside double quotes you need to use single quotes. And you need to use regular expression like .split(/=(.+)?/)
. See the output below.
$(function(){
var a = "M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode='abc'><c>string content</c></b></a>";
var b = a.split('&');
$.each(b, function (index) {
var paramsV = b[index].split(/=(.+)?/);
console.log('<input type="hidden" name="' + paramsV[0] + '" value="' + paramsV[1] + '" /> ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 27041
I this what you want to achieve, Use .split(/=(.+)/)
to only split the first =
Also notice that when you try to enter paramsV[1]
that has a "
inside it, it will break the original code of Input, that's why I replaces it with .replace(/\"/g, "''")
var a = 'M=1234&b=sdaks&c=sdkssad&strXML=<a><b mode="abc"><c>string content</c></b></a>'
var b = a.split('&');
var frm = $(".frm")
$.each(b, function(index) {
var paramsV = b[index].split(/=(.+)/);
frm.append('<input type="" name="' + paramsV[0] + '" value="' + paramsV[1].replace(/\"/g, "''") + '" /> ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="frm"></div>
Upvotes: 1