Basically, I need to convert a string
"23423,1616,3461743,1345"
to a string
"<img src='23423'></img><img src='1616'></img><img src='3461743'></img><img src='1345'></img>
So far I have tried:
var PhotoArray=JSONeventobject.Events[i].FileNameArray.split(","); // Just convert this string to array
for (i = 0; i < PhotoArray.length; i++) {
PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>";
}
var Photostring = PhotoArray.toString().replace(",", "")
But this causes my browser to crash. It makes sense to me :/
Some terrible answers here. Try:
"1,2,3,4".split(",").map(function(a) { return "<foo>" + a + "</foo>"; }).join("");
Or with slightly more modern Javascript:
"1,2,3,4".split(",").map(a => `<foo>${a}</foo>`).join("");
Also please be aware of HTML injection.
You need to make sure you close your image tag. Another thing that may cause the problem is that i is undefined. Does your browser give an error message?
var str = "23423,1616,3461743,1345";
var PhotoArray = str.split(",");
for ( var i = 0; i < PhotoArray.length; i++ ) {
PhotoArray[i] = "<img src=\"" + PhotoArray[i] + "\"></img>";
}
str = PhotoArray.join("");
There isn't an </img> tag in HTML, so you don't need that.
In PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>"; you're not ending the image tag, this will produce <img src='1616</img> which is why it gives strange results. Try PhotoArray[i] = "<img src='"+PhotoArray[i]+"'>"; instead.
If you don't want to use a loop (and I didn't want to use a loop), you could do this:
var str = "23423,1616,3461743,1345";
str = ("," + str + ",").split(',').join("'></img>,<img src='").split(",").slice(1,-1).join('');
console.log(str);
What it's doing is adding a comma on either side of the list, splitting the string into an array based on those commas, then adding the img tags on either side with the join call, splitting again based on the command between opening img tag and closing img tag we just put in, burning the first and last elements in the array, and then finally joining them all back together into a single string.
The console output is:
<img src='23423'></img><imgsrc='1616'></img><img src='3461743'></img><img src='1345'></img>
Nothing like an ugly one line solution!
In addition to what #mikel says --
You're using the same variable, i, as your index into JSONeventobject.Events and as your index into PhotoArray. Without seeing the rest of your code, I don't know whether that's going to be a problem, but it's worth checking.
Also, rather than converting to an array and back, it seems simpler to just write:
var Photostring = "<img src='" + JSONeventobject.Events[i].FileNameArray.replace(/,/g, "'/><img src='") + "'/>";
(that is, replace all the commas with '/><img src=', prefix the first element's <img src=', and append the last element's '/>).
Is the variable 'i' declared as var?
#1 str.split([separator[, limit]])
split function
splits a string into an array
based on separator we give. limit is optional.
#2 arr.map(callback[, thisArg])
map function
returns new array
that is formed
from result of
calling "callback" function
for each element in "arr".
thisArg is optional.
#1 str.split([separator[, limit]])
join function
joins all elements of an array, into a string. limit is optional.
So, answer is:
var photoString = "23423,1616,3461743,1345";
var photoArray = str.split(",").map(
function(a) {
return '<img src="' + a + '"></img>';
}
).join("");
Sources:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Related
I'm trying to make a list from info the user enters.
var todoArray = new Array();
document.getElementById("addButton").onclick = function(){
var temp = document.getElementById("inputBox").value;
var appendTemp = "<li><input type=\"checkbox\">" + temp + "</li>";
todoArray.push(appendTemp);
document.getElementById("todoListUL").innerHTML = todoArray;
console.log(todoArray);
}
But when the list times show up, they all have a comma between them, JSFiddle link for imagery here: JSFiddle
Why are they separated by this comma and how do I remove it?
When you assign any value to the .innerHTML property of an element, the value is implicitly converted to a string and then parsed as HTML. The default way that an array is converted to a string is via the .join() method, and the default array separator is a comma.
If you don't want anything, you can just call .join() yourself:
document.getElementById("todoListUL").innerHTML = todoArray.join("");
The issue is in this line:
document.getElementById("todoListUL").innerHTML = todoArray;
because the right member is converted to string and it is invoked internally the join method for todoArray array and default delimiter is comma.
Change it to
document.getElementById("todoListUL").innerHTML = todoArray.join("");
I have a string which looks likes this:
obj.property1.property2
I want the string to become
[obj][property1][property2]
Currently I use a split and later on a for loop to join each other. But I was wondering if there was a more simpler method for doing this, perhaps with using split() and join() toghether. I can't figure out how however.
Currently using:
var string = "obj.property1.property2";
var array = string.split(".");
var output = "";
for(var i = 0;i < array.length;i++) {
output += "[" + array[i] + "]";
};
console.log(output);
Consider using replace with the RegEx global option to replace all instances of '.' with back to back braces, then stick an opening and closing brace on the end like this.
var str ="obj.property1.property2"
console.log("["+str.replace(/\./g,"][")+"]")
'['+string.split('.').join('][')+']'
I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).
im trying to parse the following string;
"data[Product][0][fieldname]"
i need to be able to change the "[0]" part to a number, the "data[Product]" wont change while the "[fieldname]" will change.
im not sure how to do it with javascript but have an rough idea.
all i have which is wrong, is below but since [0] varies each time it doesnt work;
name="data[Product][0][fieldname]";
name.replace('[0]', '['+newrowid+']'
Jsfiddle;
http://jsfiddle.net/fuzzy_dunlop/8WKcs/
Use a regexp:
var a = "data[Product][0][fieldname]";
var re = /(.*\[.*\]\[)(.*)(\]\[.*\])/gi;
newstr = a.replace(re, "$1" + "YourString" + "$3");
document.write("Now: " + newstr);
Example code: http://jsfiddle.net/NKbd9/1/
Use this instead
name = name.replace('[0]', '['+newrowid+']');
Replace can take a regular expression instead of a string.
Try this:
name="data[Product][0][fieldname]";
name.replace(/\[\d\]/, '['+newrowid+']');
I assume you are trying to do this inside a loop, in that case you just need to make it dynamic. Also not that replace doesn't change the current string, it returns a new string so you need to assign the value returned back to name.
var i = 0,
len = 10,
name,
newrowid = 13;
for(; i <len; i++) {
name = "data[Product]["+i+"][fieldname]";
name = name.replace('['+i+']', '['+newrowid+']');
}
I have a JavaScript variable:
var text = "http://example.com"
Text can be multiple links. How can I put '' around the variable string?
I want the strings to, for example, look like this:
"'http://example.com'"
var text = "\"http://example.com\"";
Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:
"http://example.com"
var text = "http://example.com";
text = "'"+text+"'";
Would attach the single quotes (') to the front and the back of the string.
I think, the best and easy way for you, to put value inside quotes is:
JSON.stringify(variable or value)
You can add these single quotes with template literals:
var text = "http://example.com"
var quoteText = `'${text}'`
console.log(quoteText)
Docs are here. Browsers that support template literals listed here.
Try:
var text = "'" + "http://example.com" + "'";
To represent the text below in JavaScript:
"'http://example.com'"
Use:
"\"'http://example.com'\""
Or:
'"\'http://example.com\'"'
Note that: We always need to escape the quote that we are surrounding the string with using \
JS Fiddle: http://jsfiddle.net/efcwG/
General Pointers:
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape
character:
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
Or you can use a combination of both as shown on top.
http://www.w3schools.com/js/js_obj_string.asp
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
You can escape " with \
var text="\"word\"";
http://jsfiddle.net/beKpE/
Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:
function quote(text) {
var urls = text.split(/ /)
for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
return urls.join(" ")
}
This function takes a string like "http://example.com http://blarg.test" and returns a string like "'http://example.com' 'http://blarg.test'".
It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.
var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";
Using escape sequence of " (quote), you can achieve this
You can place singe quote (') inside double quotes without any issues
Like this
var text = "'http://www.ex.com';'http://www.ex2.com'"
Another easy way to wrap a string is to extend the Javascript String prototype:
String.prototype.quote = function() { return "\"" + this + "\""; };
Use it like this:
var s = "abc";
console.log( "unwrapped: " + s + ", wrapped: " + s.quote() );
and you will see:
unwrapped: abc, wrapped: "abc"
This can be one of several solutions:
var text = "http://example.com";
JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')