I'm working on a piece of code that uses regex expressions to do a find/replace for emoticons in a chat. However, I want to use the same array of values and output them as a reference.
The regex works fine for my searches, but when I tried to do a replace on the regex search string before I output it for my help, I still end up with a slash.
:\)
:\(
var emotes = [];
emotes[0] = new Array(':\\\)', 'happy.png');
emotes[1] = new Array(':\\\(', 'sad.png');
function listEmotes(){
var emotestext = '';
for(var i = 0; i < emotes.length; i++){
//Tried this and it doesn't seem to work
//var emote = emotes[i][0];
//emote.replace('\\', '');
emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
}
return emotestext;
}
Your problem is that str.replace doesn't change the original variable but instead returns a new one. Try this out:
var emotes = [
[':\\\)', 'happy.png'],
[':\\\(', 'sad.png']
];
function listEmotes(){
var emotestext = '';
for(var i = 0; i < emotes.length; i++){
var emote = emotes[i][0].replace('\\', ''); // See what I did here?
emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
}
return emotestext;
}
Related
I have one large string with '----begin----' and '----end----' through out the string. I am trying to seperate out each message and display them all inside a div as seperate messages. The following code gets me the first one but I am struggling with the logic to loop through a large string with many messages. How do I loop through the entire large string? Thank you.
var app = document.querySelector('#app');
function parseStr(str) {
var start_idx = str.indexOf('------Begin Message------');
var end_idx = str.indexOf('------End Message------');
app.innerHTML += '<p>' + str.substring(start_idx, start_idx + 27) + '</p>' + '<p>' +
str.substring(start_idx + 27, end_idx) + '</p><p>' +
str.substring(end_idx, end_idx + 23);
}
parseStr(str);
Below code will replace all your header and footer message text to <p> </p> tags giving you back a complete html string.
function parseStr(str) {
let beginMsg = "------Begin Message------";
let endMsg = "------End Message------";
var re1 = new RegExp(beginMsg, "gi");
var re2 = new RegExp(endMsg, "gi");
str = str.replace(re1, "<p>").replace(re2, "</p>");
return str;
}
OR if you want it this way
function parseStr(str) {
let beginMsg = "------Begin Message------";
let endMsg = "------End Message------";
var re1 = new RegExp(beginMsg, "gi");
var re2 = new RegExp(endMsg, "gi");
str = str.replace(re1, "<div><p>"+beginMsg+"</p><p>").replace(re2, "</p><p>"+endMsg+"</p></div>");
return str;
}
This while-loop should go through all messages:
function parseStr(str) {
let beginMsg = "------Begin Message------"
let endMsg = "------End Message------"
while ((let end_idx = str.indexOf(endMsg)) !== -1) {
let start_idx = str.indexOf(beginMsg);
/* start of your code */
app.innerHTML += '<p>' +
str.substring(start_idx, start_idx + beginMsg.length) +
'</p><p>' + str.substring(start_idx + beginMsg.length, end_idx) +
'</p><p>' + str.substring(end_idx, end_idx + endMsg.length);
/* end of your code */
str = str.slice(end_idx + endMsg.length);
}
}
"Large string" is a kind of trigger word for programmers. It matters if we're thinking megabytes, or just a few pages of text. In the "large, but not crazy large" case, just split on the delimiters.
const bigString = "------Begin Message------This is a message------End Message------------Begin Message------This is another message------End Message------"
const startDelim = "------Begin Message------"
const endDelim = "------End Message------"
// use a regex with a conjunction start or ("|") end delimiter
let regex = new RegExp(`${startDelim}|${endDelim}`);
// split, then filter for the messages, processing each as a <p>
let messages = bigString.split(regex).reduce((acc, el, i) => {
if (i%2) acc.push(`<p>${el}</p>`)
return acc
}, [])
console.log(messages)
If it's truly large, you might not want it in memory, and you might not want all of the parsed pieces all in the dom at once.
I would like new text, as it is fading in, to push the older text down instead of having new text appear after old text. Is this possible? Have been having a lot of difficulty figuring this out.
Here is the javascript:
var $el= $('.fader').map(function() {
return this;
}).get();
$el.forEach(function (eachdiv){
var text = $(eachdiv).text(),
words = text.split(".");
var html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + " </span>" + '<br/>';
$(eachdiv).html(html).children().hide().each(function(i){
return $(this).delay(i*200).fadeIn(200);
});
}
});
The solution does seem to involve the use of prepend, but I'm not sure where to place prepend within the code.
Try For loop like this instead of yours. Just Giving you an idea. give fadeIn effect as per your data arrives.
for (var i = 0; i < words.length; i++) {
html.prepend("<span>" + words[i] + " </span>" + '<br/>');
$(eachdiv).html(html).children().hide().each(function(i){
return $(this).fadeIn(200);
});
}
This seemed to work in the return line:
return $(this).delay(i*200).prependTo(eachdiv).fadeIn(200);
Thanks for introducing me to prepend, Sindhoor!
function generateBC(url, separator) {
var splitthis = url.split("/");
var MiddleBit = [];
var RemoveFirstElement = splitthis.shift();
var RemoveLastElement = splitthis.pop();
var RemoveLastElementDot = RemoveLastElement.substring(0, RemoveLastElement.indexOf('.')).toUpperCase();
var arrayLength = splitthis.length;
for (var i = 0; i < arrayLength; i++) {
var elementOk = splitthis[i].toUpperCase();
var urlOk = "<a href='/pictures/'>" + elementOk + "</a>";
MiddleBit.push(urlOk);
}
var ConMiddleBitS = String(MiddleBit).replace(/,/g , separator);
var completed = 'HOME ' + separator + ConMiddleBitS + separator + "<span class='active'>" + RemoveLastElementDot + "</span>" ;
document.write(completed);
}
generateBC("mysite.com/pictures/hotels/tens/holidays.html", " : ");
I don't know why I get
TypeError: Cannot call method 'replace' of undefined
at compareResults` on .replace() ?
Can someone please explain why, as I see nothing wrong with the above.
Thank-you!
It seems that you're trying to use a String method on an array. Have you tried joining the array and the using the replace() method?
var ConMiddleBitS = MiddleBit.join('').replace(/,/g , separator);
EDIT:
If you're trying to remove the , from the array you don't have to use replace, you can just do MiddleBit = MiddleBit.join(separator).
I am using the following code which displays my items from a database on the screen. I have tried adding a button to each of them using data detail as this is how i am passing data through local storage. However when i run this code i get an error message with an unexpected { in the html += line, can you not do this?
function display(results) {
article = document.getElementById("homeArticle");
var html = '';
for (var i = 0; i < results.length; i++){
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
var quant = item.P_QUANTITY;
// next I add to the string that we want to place on the page
html += '<section id="homePageSection"><div id="test"> <p>Name: ' + name + '</p><p>Description: ' + description + '</p><p>Price: £' + price + '</p><p>Quantity: ' + quant + '</p><button data-detail='{"name":"banana", "cost": "19"}'>Bananas</button></div></section>';
};
article.innerHTML = html;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var results = JSON.parse(this.responseText);
display(results.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
You need to escape the the ' around your stringed object using backslash.
Like this
'<button data-detail=\'{"name":"banana", "cost": "19"}\'>Bananas</button>'
You would need to escape the single quotes inside your string:
'</p><button data-detail=\'{"name":"banana", "cost": "19"}\'>Bananas</button></div></section>'
First of all thank you for reading this. I am having some trouble fetching the data given by the Linkedin sign-in API with javascript. Here is the script:
<script type="text/javascript">
function onLinkedInAuth() {
IN.API.Profile("me").fields(["firstName","lastName","headline","summary","location","educations","skills"]).result(displayProfiles);
}
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("name").value = member.firstName +" "+ member.lastName;
document.getElementById("pos").value = member.headline;
document.getElementById("city").value = member.location.name;
document.getElementById("sum").value = member.summary;
var i=0;
do {
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.educations.values[i].schoolName + "</td></tr>";
document.getElementById('para').innerHTML = newHTML;
i++;
}
while(i<=1);
var v=0;
do {
var oldHTML = document.getElementById('tara').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.skills.values[v].skill.name + "</td></tr>";
document.getElementById('tara').innerHTML = newHTML;
v++;
}
while(member.skills.values[v].skill.name);
document.getElementById("educ").value = member.educations.values[1].schoolName;
document.getElementById("skills").value = member.skills.values[0].skill.name;
}
</script>
It's a very basic script to get the user infos and, among it, the educational and professional background of the user. The thing is that member.educations.values[i].schoolName and member.skills.values[v].skill.name can have multiple values and I want to gather them all.
It works as long as the specified fields are not empty but then it outputs an error saying that member.skills.values[v] is undefined and it does not run the second loop.
I know the error is really basic but I'm not that great in javascript.
Thanks for your help anyways, have a good day!
You should check the length of the returned values and then loop through them as needed. Something along the lines of:
var educations = member.educations;
if(educations._total > 0) {
for(var i = 0; i < educations._total; i++) {
document.getElementById("educ").value += (i > 0) ? ', ' : '';
document.getElementById("educ").value += educations.values[i].schoolName;
}
}