I am getting stuck. Perhaps there is a better way with the regex (like to hear your thoughts).
AS a ONE-OFF the following works if I am just subbing in one thing, say -link-.
var testHtmlStr = '<tr>' +
'<td class="eve"><div class="pad" style="overflow:hidden;">' +
'<img height="50" width="80" title="{%desc%}" alt="{%desc%}" src="{%image%}">' +
'<div class="sum">{%name%}</div>' +
'{%star_rating_html%}' +
'{%eventC%}' +
'<span class="block">{%evenC%}</span>' +
'</div></td>' +
'<td class="mor"><div class="pad"><a class="mor" href="{%link%}">{%linkName%}</a>' +
'</div></td>' +
'</tr>';
var ss = 'link';
var syntax = new RegExp('(^|.|\r|\n)(\{%\s*(' + ss + ')\s*%\})',"gi");
alert(testHtmlStr.replace(syntax, '$1TESTESTESTESTS'));
The following is my code and it DOES NOT WORK. I can't figure out why. Same regex, same html template pattern. Also, my .each reiterates thru the string, but it seems after every reiteration the string returns to its unmodified state. Basically, whatever is the html string like so {%somehashkey%}, I want it to be replaced with the corresponding hash value.
I figured my code would work, can't figure out what is wrong. Something is out of wack, I know that. I can't hunt it down. Your thoughts?
(function($){
var testHTML2 = '<tr>' +
'<td class="eve"><div class="pad" style="overflow:hidden;">' +
'<img height="50" width="80" title="{%desc%}" alt="{%desc%}" src="{%image%}">' +
'<div class="sum">{%name%}</div>' +
'{%rating%}' +
'{%eventC%}' +
'<span class="block">{%evenC%}</span>' +
'</div></td>' +
'<td class="mor"><div class="pad"><a class="mor" href="{%link%}">{%linkName%}</a>' +
'</div></td>' +
'</tr>';
var type = "yahoo";
var disp = {};
disp.eventC = '5';
disp.rating = "<div>rating here</div>";
switch (type) {
case 'yahoo':
disp.link = 'http://www.yahoo.com';
disp.image = 'SOMe IMAGE' ;
disp.name = "VENICE BEACH";
disp.desc = 'MORE INFO ';
disp.linkName = 'YAHOO';
break;
default:
disp.link = 'http://www.google.com';
disp.image = 'Some IMAGE';
disp.name = "BABY BABY";
disp.desc = 'MORE INFO YOYOYO';
disp.linkName = 'GOOGLE';
}
$.each( disp, function(t, num){
var syntax = new RegExp('(^|.|\r|\n)(\{%\s*(' + t + ')\s*%\})',"gi");
testHTML2.replace(syntax, num)
});
alert(testHTML2);
})(jQuery);
You are not assigning new value to testHTML2.
testHTML2 = testHTML2.replace(syntax, num)
Related
I am returning a HTML tag in JavaScript which has values
var code = 'brand':
return `<div class="${code}_label">${code.toUpperCase()}</div>`;
I don't want to use $ and I want to concatenate through + in JavaScript
var code = 'brand':
return `<div class=code+"_label">code.toUpperCase()</div>`;
But this is not giving the expected output.
Can anyone please help?
Thanks in advance
Your quoting is a bit wrong:
function createTag() {
var code = 'brand';
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
}
console.log(createTag());
Another solution using dom api would be:
function createTag() {
var code = 'brand';
var div = document.createElement("div");
div.id = code + '_label';
div.innerText = code.toUpperCase();
return div;
}
console.log(createTag());
Without ES6 you can use single quotes:
var code = 'brand':
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
I think it's the problem with how you use quotes.
var code = 'brand':
return `<div class=` + code + `_label">` + code.toUpperCase() + `</div>`;
You are using wrong quoting.
var code = 'brand';
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
I'm trying to run the following script on a specific Wordpress page, but it's not working. The script does work but when not applied to the specific page. Yes the page id is correct. What did I do wrong? Thanks in advance.
<?php if (is_page('page-id-48857') ):?>
<script>
jQuery(document).ready(function ($) {
$(function () {
var $content = $('#jsonContent');
var data = {
rss_url: 'https://inside.calpoly.edu/feed'
};
$.get('https://api.rss2json.com/v1/api.json', data, function (response) {
if (response.status == 'ok') {
var output = '';
$.each(response.items, function (k, item) {
output += '<div class="post-card category-medium published">';
//output += '<h3 class="date">' + $.format.date(item.pubDate, "dd<br>MMM") + "</h4>";
var tagIndex = item.description.indexOf('<img'); // Find where the img tag starts
var srcIndex = item.description.substring(tagIndex).indexOf('src=') + tagIndex; // Find where the src attribute starts
var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
var srcEnd = item.description.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends
var src = item.description.substring(srcStart, srcEnd); // Extract just the URL
output += '<p class="post-meta">';
//output += '<span class="published">' + item.pubDate + '</span>';
output += '#inside.calpoly.edu</span>';
output += '</p>';
output += '<h2 class="entry-title">' + item.title + '</h2>';
//output += '<div class="post-meta"><span>By ' + item.author + '</span></div>';
var yourString = item.description.replace(/<img[^>]*>/g,""); //replace with your string.
var maxLength = 300 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
output += '<div class="excerpt">'+trimmedString + '</div>';
output += 'Read More';
output += '<a class="entry-featured-image-url" href="'+ item.link + '"><img src="' + src + '"></a>';
output += '</div>';
return k < 1;
});
$content.html(output);
}
});
});
</script>
<?php endif; ?>
You are passing in an invalid ID to the is_page() function.
Based off of your code sample, you should be using an integer for your post ID and not a string and also not the 'page-id' portion.
https://developer.wordpress.org/reference/functions/is_page/
Here's some example usages:
// When any single Page is being displayed.
is_page();
// When Page 42 (ID) is being displayed.
is_page( 42 );
// When the Page with a post_title of "Contact" is being displayed.
is_page( 'Contact' );
// When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( 'about-me' );
In your case you should be using:
<?php if (is_page(48857) ):?>
WordPress' is_page() function requires a "Page ID, title, slug, or array of such.". 'page-id-48857' is the body class, you need to just use is_page( 48857 ) since the actual ID is just 48857.
Also note that you should seriously consider using wp_enqueue_script() instead of coding in a custom script tag. It will save you countless headaches in the future.
I wanted to get the profile photos per post of this site (https://medium.com/#femalefounderssg) using this javascript function but I am not getting the right photo. Please guide me in changing my code for me to get the appropriate photo. Thank you. Here is the code.
$(function () {
var $content = $('#jsonContent');
var data = {
rss_url: 'https://medium.com/feed/#femalefounderssg'
};
$.get('https://api.rss2json.com/v1/api.json', data, function (response) {
if (response.status == 'ok') {
var output = '';
$.each(response.items, function (k, item) {
var visibleSm;
if(k < 3){
visibleSm = '';
} else {
visibleSm = ' visible-sm';
}
output += '<div class="col-sm-6 col-md-4' + visibleSm + '">';
output += '<div class="blog-post"><header>';
output += '<h4 class="date">' + $.format.date(item.pubDate, "dd<br>MMM") + "</h4>";
var tagIndex = item.description.indexOf('<img'); // Find where the img tag starts
var srcIndex = item.description.substring(tagIndex).indexOf('src=') + tagIndex; // Find where the src attribute starts
var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
var srcEnd = item.description.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends
var src = item.description.substring(srcStart, srcEnd); // Extract just the URL
output += '<div class="blog-element"><img class="img-responsive" src="' + src + '" width="360px" height="240px"></div></header>';
output += '<div class="blog-content"><h4>' + item.title + '</h4>';
output += '<div class="post-meta"><span>By ' + item.author + '</span></div>';
var yourString = item.description.replace(/<img[^>]*>/g,""); //replace with your string.
var maxLength = 120 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
output += '<p>' + trimmedString + '...</p>';
output += '</div></div></div>';
return k < 3;
});
$content.html(output);
}
});
});
Current Profile Output:
Desired Profile Output:
You are getting the wrong image because the first result you get when searching for <img index is the author's image.
You need to skip the first result and get the second one:
Finding second occurrence of a substring in a string in Java [it's Java, but the concept remains]
var tagIndex = item.description.indexOf('<img', item.description.indexOf('<img') + 1);
String#indexOf supports a second argument as "fromIndex".
By adding 1 to the index of the first result we make sure that the first <img will not match, and instead the second <img will.
Simplified JSFiddle: https://jsfiddle.net/yuriy636/03n1hffh/
I'm having problems with my script and i can't see the problem with it myself:
$("#mainsub").append(newRow + "<div class='showMore' onclick='document.dispatchEvent(expand, { 'postId': " + pf.id + " })'>Show More</div></div>");
My webkit debugger is saying: "Uncaught SyntaxError: Unexpected token ;" when i click on the element.
has anyone run into this before? is there a problem with the line of code?
EDIT:** newRow looks like this:
var newRow = "<div id=" + pf.id + ">"+rowContents;
rowContents is:
rowContents += "<div class='"+tagName+"'>"+tag.text()+"</div>";
tag name is just from some xml i am parsing.
Another edit: I'm just going to put the whole function in just in case this is helpful
pf.parseResults = function(){
$("#mainsub").empty();
var $xml = $(pf.xml);
var $query = $xml.find('query_result').children().each(function() {
var row = $(this);
var rowContents = "";
row.children().each(function() {
var tag = $(this);
var tagName = tag[0].tagName;
if(tagName != "ID"){
rowContents += "<div class='"+tagName+"'>"+tag.text()+"</div>";
}
if(tagName === "ID"){
pf.id = tag.text();
}
});
var newRow = "<div id=" + pf.id + ">" + rowContents;
$("#mainsub").append(newRow + "<div class='showMore' onclick='document.dispatchEvent(expand, { \'postId\': " + pf.id + " })'>Show More</div></div>");// this fires an event with data attached listing the id of the element the user tapped/**/
});
$("#mainsub").append("<div onclick='document.dispatchEvent(nextPage)'><p>Next</p></div>");// figure out how to not show next when there will not be another page
if(pf.getPage > 0){
$("#mainsub").append("<div onclick='document.dispatchEvent(previousPage)'><p>Previous</p></div>");// show go to previous as long at it will exist
}
};
When you nest quotes of the same type (single quotes in your case) you have to escape them like this:
$("#mainsub").append(newRow + "<div class='showMore' onclick='document.dispatchEvent(expand, { \'postId\': " + pf.id + " })'>Show More</div></div>");
As this line of code is quite long and I didn't wand to change too much, I'll point out that escaped quotes are in this expand, { \'postId\': " + pf.id + " } fragment.
I am trying to convert emoticon codes into emoticon images. I want to write it within a function. Here is original code without function yet :
$.get("showMsgLive.php?username=" + str + "&servertime=" + servertime + "&usertime=" + usertime + "&lastmsgID=" + lastmsgid, function(newitems){
newitems = newitems.replace(/\(smile1\)/g, '<img src="images/emoticons/emobasic/smile1.gif" class="emoticon"/>')
.replace(/\(rabbit18\)/g, '<img src="images/emoticons/emospecial/rabbit18.gif" class="emoticon"/>')
.replace(/\(rabbit19\)/g, '<img src="images/emoticons/emobasic/rabbit19.gif" class="emoticon"/>')
.replace(/\(rabbit20\)/g, '<img src="images/emoticons/emoadvance/rabbit20.gif" class="emoticon"/>')
.replace(/\(sheep4\)/g, '<img src="images/emoticons/emospecial/sheep4.gif" class="emoticon"/>'); //end of special emo
newitems.innerHTML = newitems;
api.getContentPane().append(newitems);
});
Here is the code that I try to write it in function :
function convertTextEmo(newitems){
newitems = newitems.replace(/\(smile1\)/g, '<img src="images/emoticons/emobasic/smile1.gif" class="emoticon"/>')
.replace(/\(rabbit19\)/g, '<img src="images/emoticons/emospecial/rabbit19.gif" class="emoticon"/>')
.replace(/\(rabbit20\)/g, '<img src="images/emoticons/emobasic/rabbit20.gif" class="emoticon"/>')
.replace(/\(sheep4\)/g, '<img src="images/emoticons/emoadvance/sheep4.gif" class="emoticon"/>'); //end of special emo
return newitems;
}
jQuery.get("showMsgLive.php?username=" + str + "&servertime=" + servertime + "&usertime=" + usertime + "&lastmsgID=" + lastmsgid, function(newitems){
convertTextEmo(newitems);
api.getContentPane().append(newitems);
});
I didn't put innerHTML in the function because I don't know where and how to put it, and the output didn't success convert the code into image. May I know where or how to put innerHTML in the function and return the value?
newitems.innerHTML = newitems; should not even work as newitems is a string and not an HTML element.
I think all you have to do is:
api.getContentPane().append(convertTextEmo(newitems));
Another tip to improve your code: As the image names of are the same as identifiers in the text, you could just create an array of names:
var emoticons = ['smile1', 'rabbit18',...];
and loop over it:
function convertTextEmo(newitems, icons){
var pattern, content;
for(var i = icons.length; i--; ) {
pattern = new RegExp('\(' + icons[i] + '\)', 'g');
content = '<img src="images/emoticons/emospecial/' + icons[i] + '.gif" class="emoticon"/>';
newitems = newitems.replace(pattern, content);
}
return newitems;
}
jQuery.get("showMsgLive.php?username=" + str + "&servertime=" + servertime + "&usertime=" + usertime + "&lastmsgID=" + lastmsgid, function(newitems){
newitems = convertTextEmo(newitems);
api.getContentPane().append(newitems);
});
Your function returns the modified HTML.