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);
Related
I have the following function:
function parseEntry(query, html, url) {
// logic draft :(
var re = new RegExp('{{{(.*)}}}');
regex = query.replace(re, "$1");
var newre = new RegExp(regex);
regged = html.replace(newre, "$1");
ret = query.replace(regex, regged);
// parse selectors
var re = new RegExp('{{(.*)}}');
newtext = html.replace(re, "$1");
ret = ret.replace(newtext, $(newtext).clone().html());
// parse %url%
ret = ret.replace("%url%", url);
// ret remaining
return ret;
}
// Called this way:
let output = parseEntry('static value %url% {{.thisclass}} {{{(\d+)}}}', '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12', "http://perdu.com");
console.log(output)
/**
should return:
static value http://perdu.com TestTest2 123412
{{{triple brackets = regex}}}
{{double brackets = jquery}}
**/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Can you help refactoring parseEntry() function to return expected output?
All help appreciated!
I'm not sure if I undersand, but this is an attempt using different approaches I think are useful in this kind of situations. There are examples of split(), replace() and the createElement hack to parse html.
var query = 'static value %url% {{.thisclass}} {{{(\d+)}}}';
var html = '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12';
var url = "http://perdu.com";
query = query.split(" ").map(o=>{
return o.replace(/\{\{\{(.*)\}\}\}/g, "$1");
}).map(o=>{
return o.replace(/\{\{(.*)\}\}/g, "$1");
});
var el = document.createElement( 'div' );
el.innerHTML = "<div class='outer'>"+html+"</div>";
var t1 = $("h1").text();
var t2 = $("h2").text();
var out = $(".outer").text();
var newArr = [];
newArr.push(query[0]+" "+query[1]+" "+url+" "+t1+t2+out);
newArr.push("{{{triple brackets = "+query[4]+"}}}");
newArr.push("{{double brackets = "+query[3]+"}}");
console.log(newArr);
newArr.map(o=>{
$("#res").append(o+"<br>");
});
Full example here: http://jsfiddle.net/k8em5twd/6/
So if this question is as simple as "why didn't the backslash show up in my output", then the answer is also very simple. Try escaping the backslash in your input string like so:
let output = parseEntry('static value %url% {{.thisclass}} {{{(\\d+)}}}', '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12', "http://perdu.com");
The key is that {{{(\d+)}}} becomes {{{(\\d+)}}}. This way the slash is recognized as a character. Otherwise, \d is treated as an escape sequence. Output below.
function parseEntry(query, html, url) {
// logic draft :(
var re = new RegExp('{{{(.*)}}}');
regex = query.replace(re, "$1");
var newre = new RegExp(regex);
regged = html.replace(newre, "$1");
ret = query.replace(regex, regged);
// parse selectors
var re = new RegExp('{{(.*)}}');
newtext = html.replace(re, "$1");
ret = ret.replace(newtext, $(newtext).clone().html());
// parse %url%
ret = ret.replace("%url%", url);
// ret remaining
return ret;
}
// Called this way:
// THIS LINE IS CHANGED:
let output = parseEntry('static value %url% {{.thisclass}} {{{(\\d+)}}}', '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12', "http://perdu.com");
console.log(output)
/**
should return:
static value http://perdu.com TestTest2 123412
{{{triple brackets = regex}}}
{{double brackets = jquery}}
**/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ended up doing it myself, for the curious:
function parseEntry(query, url, ht) {
// parse regex expressions (triple brackets)
var re = new RegExp('{{{(.*)}}}', 'g');
q = query.match(re);
for (qq in q) {
var newregex = q[qq].replace("{{{", '').replace("}}}", '');
newregex = new RegExp(newregex, 'g');
newq = ht.match(newregex).join("");
query = query.replace(q[qq], newq);
}
// parse jquery expressions (double brackets)
re = new RegExp('{{(.*)}}', 'g');
q = query.match(re);
for (qq in q) {
var newjq = q[qq].replace("{{", '').replace("}}", '');
code = $('<div>'+ht+'</div>').find(newjq);
appendHTML = '';
code.each(function() {
appendHTML += $(this).html();
})
query = query.replace(q[qq], appendHTML);
}
// parse %url%
ret = query.replace("%url%", url);
// ret remaining
return ret;
}
let output = parseEntry('static value %url% {{.thisclass}} {{{(\\d+)}}}', "http://perdu.com", '<h1 class="thisclass">Test</h1><h2 class="thisclass">Test2</h2> 1234 12');
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm building one site at JOOMLA and at this site i want to put all the word "Inovflow" on the site, at the color blue and upercase. Like this "INOVFLOW".
I put this code on the js folder of the site:
jQuery(document).fn.findText = function(params){
var phrases = params.query,
ignorance = params.ignorecase;
wrapper = $(this);
var source = wrapper.html();
selection_class_name = params.style;
source = source.replace(/[\n|\t]+/gi, '');
source = source.replace(/\s+/gi, ' ');
source = source.replace(/> /gi, '>');
source = source.replace(/(\w)</gi, function(m, w){return(w + " <");});
phrases.forEach(function(str){
var regexp = makeRegexp(str);
source = source.replace(regexp, function (m){
return (emulateSelection(m));
});
});
wrapper.html(source);
var res_array = wrapper.find("[search=xxxxx]")
return(res_array);
};
function makeRegexp(s){
var space = '( )?(<span[^>]*>)?(</span[^>]*>)?( )?';
var result = s.replace(/\s/gi, space);
result = new RegExp(space + result + space, "gi");
return(result);
}
function emulateSelection (htmlPiece){
htmlPiece = htmlPiece.replace(/(?!=>)[^><]+(?=<)/g, function(w){
return(wrapWords(w));}
);
htmlPiece = htmlPiece.replace(/^[^><]+/, function(w){
return(wrapWords(w));}
);
htmlPiece = htmlPiece.replace(/[^><]+$/, function(w){
return(wrapWords(w));}
);
htmlPiece = htmlPiece.replace(/^[^><]+$/, function(w){
return(wrapWords(w));}
);
return( htmlPiece );
}
function wrapWords(plainPiece){
console.log("plain: " + plainPiece);
var start = '<span search="xxxxx">',
stop = '</span>';
return(start + plainPiece + stop);
}
jQuery(document).each($('.container').findText({query: ['INOVFLOW']}), function (){
$(this).addClass("changeColorInovflow");
});
After this, the page seems to get on a Infinite loop and doesn't load.
if instead of jQuery(document) I use $. the JS returns a error and doesn't run.
Am I doing something wrong?
If findText is intended to be a jQuery plugin, you'll need to update the way the function is declared.
$.fn.findText = function(params) {
var phrases = params.query;
// removed unused 'ignorance' var
var wrapper = this; // this is already a jQuery object
var source = wrapper.html();
selection_class_name = params.style;
source = source.replace(/[\n|\t]+/gi, '');
source = source.replace(/\s+/gi, ' ');
source = source.replace(/> /gi, '>');
source = source.replace(/(\w)</gi, function(m, w){return(w + " <");});
phrases.forEach(function(str){
var regexp = makeRegexp(str);
source = source.replace(regexp, function (m){
return (emulateSelection(m));
});
});
wrapper.html(source);
var res_array = wrapper.find("[search=xxxxx]")
return this; // return 'this' to make it chainable
}
Here are the relevant docs:
https://learn.jquery.com/plugins/basic-plugin-creation/
Then, when you call findText, you can use a much simpler selector:
$('.container').each(function() {
$(this).findText({query: ['INOVFLOW']}).addClass("changeColorInovflow");
});
The original code wouldn't work because each() takes either a function or an array with a callback as parameters, not a selector.
.each(): http://api.jquery.com/each/
jQuery.each(): http://api.jquery.com/jquery.each/
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));
var api = "/self/{code}/my/{id}";
var code = "GHUYFUYI";
var id = 12346;
Hi i'm new to Jquery...any help is appreciated.
Using above API path data how can we generate URL like given below using JQuery?
Thanks in advance....
Result:
/self/GHUYFUYI/my/12346
var api = "/self/{0}/my/{1}";
var array = new Array("GHUYFUYI",12345);
for (var i = 0; i < array.length; i++) {
api = api.replace("{"+i+"}",arr[i]);
}
cosole.log(api);
you can do something like this.
You don't need jQuery for this. Just plain old Javascript...
var api = "/self/{code}/my/{id}";
var code = "GHUYFUYI";
var id = 12346;
api = api.replace("{code}", code).replace("{id}", id);
Your best bet would be to use regular expressions. Here's a simple example:
var api = "/self/{code}/my/{id}";
var code = "GHUYFUYI";
var id = 12346;
api = api.replace(/{code}/, code).replace(/{id}/, id);
You can use the javascript function Replace (http://www.w3schools.com/jsref/jsref_replace.asp)
api = api.replace("{code}", code).replace("{id}", id);
Enhance string prototype
if (!String.prototype.format) {
String.prototype.format = function() {
var str = this.toString();
if (!arguments.length)
return str;
var args = typeof arguments[0],
args = (("string" == args || "number" == args) ? arguments : arguments[0]);
for (arg in args)
str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
return str;
}
}
Usage
var formatData = {
code:"GHUYFUYI",
id:12346
};
var api = "/self/{code}/my/{id}".format(formatData);
Credits: Gabriel Nahmias
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};