I have a text that includes mani list items on the next format:
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>..."
I'm trying to create JSON on the next format:
{
name: "M3-2200",
Model: "M3-2200"
}
I'm trying using next code, but it doesn't work my problem is on push. anybody can explain me how do it right?
result ={};
while(text.indexOf("<li>")!== -1){
var listi = text.substring(text.indexOf("<li>"), text.indexOf("</li>"));
var model = listi.substring(0, listi.indexOf("(") -1);
var name = listi.substring(listi.indexOf("("), listi.indexOf(")"));
var item = {name: name: model : model};
result.push(item);
var text = text.substring(text.indexOf("</li>"));
}
Other solution for your problem:
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
var result = JSON.parse('[' +
text.replace(/(<li>|<\/li>| \(|\))/g, function(_, part){
switch (part) {
case '<li>': return '{"name":"';
case '</li>': return '},';
case ' (': return '", "Model":"';
case ')': return '"';
}
}) + '0]').slice(0, -1);
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
JSONStr = text.trim().replace(/<li>/g,"{\"name\":\"").replace(/ \(/g,"\" , \"model\":\"").replace(/\)\<\/li\>/g,"\"},");
JSONStr = "["+JSONStr.substring(0,JSONStr.length-1)+"]";
console.log(JSONStr);
Will the above code work?
I hope I understand your question correctly. If this is the output you want:
[{"name":"M3-2200 ","model":"da2/M3-2200"},{"name":"N3-2200 ","model":"da2/N3-2200"},{"name":"Picasso ","model":"picasso/A500"},{"name":"Picasso ","model":"picasso/A501"},{"name":"Picasso ","model":"ventana/A500"}]
Then this is a way to do it:
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
var extractItem = function (item) {
var partsArray = /(.+) ?\((.+)\)\<\/li>/.exec(item)
if(partsArray) return {"name":partsArray[1], "model":partsArray[2]}
}
var result = text.split('<li>')
.map(extractItem)
.filter(function(e){return e != undefined});
console.log(JSON.stringify(result));
Related
I have string like below:
var str ='video AND music NOT movie AND moble NOT laptop';
Above string split after AND and NOT and store in 2 different arrays.
After AND text in different array.
After NOT text different array dynamically.
Output looks like
["video","music","mobile"],["movie","laptop"]
function haveAndNots(str) {
var nots = [];
str = str.replace(/NOT (\w+)/g, function(m, c) {
nots.push(c);
return '';
});
return {
have: str.split('AND').map(str => str.trim()),
nots: nots
}
}
var str = 'video AND music NOT movie AND mobile NOT laptop';
var split = haveAndNots(str);
console.log(split.have);
console.log(split.nots);
Use split function.
var str = 'video AND music NOT movie AND moble NOT laptop';
var strAnd = [];
var strNot = [];
var temp = str.split(' ');
$.each(temp, function(key, value) {
if (value === 'AND') {
strAnd.push(temp[key + 1])
} else if (value === 'NOT') {
strNot.push(temp[key + 1])
}
});
console.log(strAnd,strNot);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var rawString = '<a>This is sample</a><img src="example1.com" /></br><img src="example2.com" /><p>String ends.</p>'
var output = somefunction(rawString);
output should be:
output = ["example1.com","example2.com"];
I didn't find any solution here. I tried using few regex but couldn't work perfactly.
Here are stackoverflow few answers:
https://stackoverflow.com/a/12393724/4203409
https://stackoverflow.com/a/25632187/4203409
Thanks in advance.
Using Javascript and regex:
function getAttrFromString(str, node, attr) {
var regex = new RegExp('<' + node + ' .*?' + attr + '="(.*?)"', "gi"), result, res = [];
while ((result = regex.exec(str))) {
res.push(result[1]);
}
return res;
}
Example usage:
var rawString = '<a>This is sample</a><img src="example1.com" /></br><img src="example2.com" /><p>String ends.</p>';
getAttrFromString(rawString, 'img', 'src');
Returns:
["example1.com", "example2.com"]
Here is your jsfiddle
You can use jQuery(), .filter(), .map(), .get()
var output = $(rawString).filter("img").map(function() {return this.src}).get();
.Filter work with this example
var rawString = '<a>This is sample</a><img src="example1.com" /></br><img src="example2.com" /><p>String ends.</p>';
var indices = new Array();
var result = $(rawString).filter('img').map(function() {
indices.push(this.src);
});
console.log(indices);
.find Will work with this example
var rawString = "<style></style><div><div><div class=''><div class=''><div style='position:relative'><div id='' class='sideCross'>X</div> <div class=\"vertical-text\">Live Chat</div><img src=\"http://localhost/rcm/dashboard\" alt=\"text\"/><div class=\"speech-bubble\"><img src=\".com\" alt=\"text\"/></div></div></div></div></div> </div>";
var indices = new Array();
var result = $(rawString).find('img').map(function() {
indices.push(this.src);
});
console.log(indices);
I am trying to do something crazy, I have a JSON object of all sorts of rules for my website. I have a system set up where I can write pseudo code and then it turns it into actual code. I have this working perfectly for strings, however now I need to be able to pass functions, and replace the pseudo code inside of functions, then execute the functions.
I think I am on the right track, however when I turn a function to a string it only turns the output of the functions into a string.
Here's my JSON (part of it)
customValidation: {
//compare: "(<!this!> && <!PrimeTimeDiscount!> == 200) || (<!PrimeTimeDiscount!> == 100)",
compare: function(){
return new Validator()["date"]("<!this!>", 50);
},
overrideDefault: true
}
The commented out "compare" is how I use this system for regular strings.
And below is how I handle turning "<!this!>" and "<!*!>" into values from the JSON object. It is basically the same code twice, but the one below I have started modifying for when a function is detected.
if(typeof customValidationRule != "function")
{
var string = customValidationRule.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRule;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
}
else
{
var customValidationRuleString = customValidationRule().toString();
var string = customValidationRuleString.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRuleString;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
var backToFunction = eval('(' + execCustomValidationRule + ')');
//validation = customValidationRule();
}
validation = eval(execCustomValidationRule);
I have a string <ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul> and on client side I have to convert it to JSON. Something like {data:['Foo','Bar'],params:['100;50','200;150']}
I found a pretty good way to achieve it in here so my code should be something like that
var $input = $(input);
var data = "data:[";
var params = "params:[";
var first = true;
$input.find("li").each(function() {
if (!first) {
data += ",";
params += ",";
} else {
first = false;
}
data += "'" + $(this).text() + "'";
var e = $(this).attr("e");
var n = $(this).attr("n");
params += "'" + e + ';' + n + "'";
});
return "{data + "]," + params + "]}";
But the problem is that I can't use jquery. How can I do the same thing with prototype?
You want to use a DOM parser:
https://developer.mozilla.org/en/DOMParser
Something like this...
var xmlStr = '<ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul>';
var parser = new DOMParser();
var doc = parser.parseFromString(xmlStr, "application/xml");
var rootElement = doc.documentElement;
var children = rootElement.childNodes;
var jsonObj = {
data: [],
params: []
};
for (var i = 0; i < children.length; i++) {
// I realize this is not how your implementation is, but this should give
// you an idea of how to work on the DOM element
jsonObj.data.push( children[i].getAttribute('e') );
jsonObj.params.push( children[i].getAttribute('n') );
}
return jsonObj.toJSON();
Also, don't manually build your JSON string. Populate an object, then JSON-encode it.
Edit: Note that you need to test for DOMParser before you can use it. Check here for how you can do that. Sorry for the W3Schools link.
Why you are building an array object with string? Why not
var data = new Array();
var params = new Array();
$$("li").each(function() {
data.push ($(this).text());
params.psuh($(this).attr("e") + ";" + $(this).attr("n"));
});
return {data:data.toString(), params:params.toString()};
or
return {data:data, params:params};
i want to strip just text values from below html with js.
var Str = "<span style="">MY name is KERBEROS.</span><B>HELLO Everbody</B>"
All text strips with codes that is below;
[^<>]+(?=[<])
But i want to strip just UPPERCASE words. Clresult must be: MY, KERBEROS, HELLO
Thank you already now for your suggestions.
Regards,
Kerberos
Here is your code, gives output: MY,KERBEROS,HELLO
<script>
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "");
};
String.prototype.getUpperCaseWords = function()
{
var matchTag1 = /\b([A-Z])+\b/g;
var o = this.match(matchTag1);
return o;
};
var Str = "<span style=''>MY name is KERBEROS.</span><B>HELLO Everbody</B>";
var out1 = Str.stripHTML();
var out2 = out1.getUpperCaseWords();
alert(out2);
</script>
This is another solution in JavaScript using just one line of regex:
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "").match(/\b([A-Z])+\b/g);
};
var Str = "<span style=''>MY name is SATYA PRAKASH.</span><B>HELLO Everyone</B>";
var out1 = Str.stripHTML();