Concat string dynamically Javascript - javascript

I should concatenate an HTML string (i.e. "<div>HTML string</div>") to compose dinamically a description for Guider-JS.
I tried to do that using concat method but doesn't work.
var str = "<div><p>first test:</p><ul>";
for(var i=0; i<list.length;i++){
str+=("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");
}
console.log("one " + str);
Otherwise, if I use += operator works well.
var str = "<div><p>second test:</p><ul>";
for(var i=0; i<list.length;i++){
str.concat("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");
}
console.log("two " + str);
I have made a fiddle for explain better the case.
Sorry for my question, maybe is trivial but i don't understand why this happen

String#concat returns the new string with the concatenated values, so you want to assign that result to str: str = str.concat(...
Note that if you're using concat, you don't need + anymore:
str = str.concat("<li class='pointer' onclick=alert('hello')>", list[i], "</li>");
// -----------------------------------------------------------^^-------^^

Check the updated fiddle
make it
str = str.concat("<li class='pointer' onclick=alert('hello')>" + list[i] + "</li>");

Related

How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}

Get specific part of url

I have a set of urls that i need to get a specific part of . The format of the url is :
http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg
I need to get the 1234567 bit and store that in a var.
Well you can do splits
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".split("/").pop().split("_").shift()
or a regular expression
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".match(/\/(\d+)_\d+\.jpg$/).pop()
You should be able to get it to work with your JSON string by checking the URL with a function. Something like this should work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
$.get("test.php", function (data) {
// now you can work with `data`
var JSON = jQuery.parseJSON(data); // it will be an object
$.each(JSON.deals.items, function (index, value) {
//console.log( value.title + ' ' + value.description );
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
//tr.append("<td>" + value.description + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td class='temperature'>" + value.temperature + "</td>");
tr.append("<td>" + "<a href='" + value.deal_link + "' target='_blank'>" + "View Deal</a>" + "</td>");
myvar = checkForMatches(value.deal_link);
if(myvar == false) {
myvar = value.deal_link; //if no matches, use the full link
}
tr.append("<td>" + "<a href='" + myvar + "' target='_blank'>" + "Go To Argos</a>" + "</td>");
$('table').append(tr);
});
});
Earlier, more basic examples.
You can use a regular expression to find the match.
Something like this would work:
var str = "http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg";
var res = str.match(/.*\/(.*)_1.jpg/);
alert(res[1])
If you wanted to go a little further with it, you could create a function and pass the strings you wanted to test, and it would return the matched value if found, or boolean false if no matches exist.
Something like this would work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
alert(checkForMatches("http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg"))
alert(checkForMatches("this is an invalid string"))
You can see it working here: https://jsfiddle.net/9k5m7cg0/2/
Hope that helps!
var pathArray = window.location.pathname.split( '/' );
to split 1 / 2/ 3/ 4...
So to get path 2 it would be:
var setLocation = pathArray[1];
Well This should do
function getLastFolder(){
var path = window.location.href;
var folders =path.split("/");
return folders[folders.length-1]);
}
Here's the idea: take everything that comes after the final / character, and then take everything within that substring that comes before the first _ character.
var getUrlTerm = function(url) {
var urlPcs = url.split('/');
var lastUrlPc = urlPcs[urlPcs.length - 1];
return lastUrlPc.split('_')[0];
}
You can attribute the url to an 'A' element and use javascript's built in methods to make your life easier:
var parser = document.createElement('a');
parser.href = "YOUR URL HERE";
var fileName = parser.pathname.split('/').pop();
var code = fileName.split('_')[0];
code will have the value you want.
I would use a regular expression and sense it seems you are looking for numbers you can do the regex filter for that.
var path = window.location.pathname,
regFilter = /\d*/g,
filter = regFilter.exec(path);
The regular expression \d narrows your filter search to only look for digits. And the * grabs the group of digits.
Your result is in the filter var. The only thing about this is that the exec returns an array with your original string and the returned result which will be at the 1 index so you'll have to grab it from there like so.
filter[1];

Dynamically add text strings with increasing number to a div

I'm trying add some text strings with increasing number to a div,
for example:
<div>
Text String n°: 1
Text String n°: 2
Text String n°: 3
etc...
</div>
but somethings does not work properly:
var StringsContainer = document.getElementById('StringsContainer');
var createTextStrings = function(){
var i = 0
while(i < 3){
i++;
console.log("String n°:" + (i + 1));
document.body.innerText = "String n°:" + (i + 1);
}
};
createTextStrings();
Demo: http://jsfiddle.net/Y5z6K/
In the console.log I can see a similar result, but it still not works.
Solution:
Here updated perfect result wanted: http://jsfiddle.net/Y5z6K/4/
Just change append the string:
document.body.innerText += "String n°:" + (i) +"\n";
Full code:
var StringsContainer = document.getElementById('StringsContainer');
var createTextStrings = function () {
var i = 0
while (i < 4) {
i++;
console.log("String n°:" + (i));
document.body.innerText += "String n°:" + i + "\n";
}
};
createTextStrings();
Also, you don't need i + 1 as i is already incremented.
Demo: http://jsfiddle.net/Y5z6K/1/
Concatenate the strings as you are looping:
document.body.innerText += "String n°:" + i + "\n";
Plus, you don't need to i++ then adding another i +1 when displaying it. So, just drop the +1 on the string display.
UPDATED: adding "\n" for the line change.
See the fiddle at:
JSFiddle
Try this out: http://jsfiddle.net/Y5z6K/2/
JS:
var StringsContainer = document.getElementById('StringsContainer');
var createTextStrings = function () {
var i = 0
while (i < 3) {
console.log("String n°:" + (i + 1));
document.body.innerHTML += "String n°:" + (i + 1) + "<br\>";
i++;
}
};
createTextStrings();

Using a for loop with JSON

Should be very simple, but I only get Jimmy cricket output and I'm expecting all the names in li tags. Thanks for any help.
<ul id="members"></ul>
<script>
var teammembers = [
{"name":"John Doe", "profile":"/img/profile/user1.jpg", "position":"President", "email":"email#example.com", "phone":"242-abcd"},
{"name":"James Bond", "profile":"/img/profile/user2.jpg", "position":"Vice President", "email":"007#example.com", "phone":"242-0007"},
{"name":"Jimmy Cricket", "profile":"/img/profile/user3.jpg", "position":"Vice Cricket", "email":"cricket#example.com", "phone":"242-wxyz"}
];
for (var i = 0; i < teammembers.length; i++) {
document.getElementById("members").innerHTML = "<li>" + teammembers[i].name; + "</li>"
}
</script>
The = sign here is replacing the innerHTML on each iteration. Hence you see the last value of the array here.
Convert it to a +=. Like this,
document.getElementById("members").innerHTML += "<li>" + teammembers[i].name; + "</li>"
+= will append it.
You need to append to the innerHTML, rather than set it. Instead of this:
document.getElementById("members").innerHTML = "<li>" + teammembers[i].name; + "</li>"
use this (the change is from using = to using +=):
document.getElementById("members").innerHTML += "<li>" + teammembers[i].name; + "</li>"

How to replace strings from an array

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;
}

Categories