I have a code like this:
var exist_file = document.getElementById('exist_file').value;
document.getElementById('dialog-confirm-upload').innerHTML=
"The file" +
for (var i=0;i<exist_file.length;i++){
exist_file + ","
}
+
"has been already transferred? Do you want to overwrite?"
exist_file is an array which contains one or more than one element: ['hello', 'ok']. I want to pass the value to innerHTML like this.
"The file hello, ok has been already transferred? Do you want to overwrite?" I tried the following above code but it turns out that's not a valid syntax. How can I achieve this?
First you have to parse the string into an array, then you can format it with commas:
var exist_file = document.getElementById('exist_file').value;
document.getElementById('dialog-confirm-upload').innerHTML=
"The file " +
exist_file.substr(3, exist_file.length - 5).split("', u'").join(", ") +
" has already been transferred. Do you want to overwrite?"
Note: This is the most basic form of parsing. It works with strings containing regular characters, but escaped characters are not unescaped.
var exist_file = document.getElementById('exist_file').value,
msg = "The file" + exist_file.toString() + "has been already transferred? Do you want to overwrite?";
document.getElementById('dialog-confirm-upload').innerHTML= msg;
This snippet works for both cases where exist_file is an array or a string.
Related
I am trying to directly write a Javascript variable assignment code on a ASP.NET web page.
Response.Write("<script>itHtml = '");
Response.Write("<div id=\"pop_ctrl\">Select</div><ul id=\"demo_ul\">");
foreach (Article a in arts)
{
Response.Write("<li class=\"demo_li\"><a onclick=\"ShowArticleCard(" + a.Id + ",\'" + a.User + "\',\'" + a.DateString + "\'); return false\"><div>" + it.User + "</div> <div>" + it.Title + "</div></a></li>");
}
Response.Write("</ul>");
Response.Write("';</script>");
Anchor tag in this markup executes a function ShowArticleCard() on click. This function accepts one int and two string parameters. When I am trying to add a C# string variable in place of string parameters, it replaces them like a JavaScript keyword. I tried using ',\' and \", but error persists. So, are there any levels of nested quotes we can use? If not how can I resolve this?
Try wrapping the actual value (parameter) in the quotes, like this,
onclick=\"ShowArticleCard(" + a.Id + ",'" +
a.User + "','" + a.DateString + "'); // Remaining code
Changed
I have removed the single quotes from the int type param, and removed the escape slash from the string types. They can be simply put as, '. Now when the code would run, it would be considered as a string. Otherwise (if the value is numeric) then ignore these quotes and enter them as they are. Only string-type data requires to be wrapped in either ' or ". In JavaScript they are same. In C#, ' and " have different meanings, you know that well.
Tip: Also, if you are writing something for client-side rendering, like in ASP.NET, you can easily write it as,
string.Format("<a href='{0}' onclick='func({1})'>My Link</a>",
hyperlink, param);
This would be rendered as you want it to be. :) The single quotes would be converted to double quotes once rendered in your browser. Or you can use # before the string, and write " inside the string without having to escape them.
I figured out a way of doing this. I don't know why it didn't came in my mind before.
I enclosed JavaScript function's string parameters with \\'. Like this:
ShowArticleCard(" + a.Id + ",\\'" + a.User + "\\',\\'" + a.DateString + "\\');
So that the resultant code will be:
ShowArticleCard(someid,\'someUser\',\'someDateString\');
I'd like to know if I can parse & filter JSON text data based on a regular expression; say for example I have the following
{"key":"some:xx:yy", "value": 72311}
{"key":"some:xx:zz", "value": 72311}
{"key":"some:xx:qq", "value": 72311}
I want to select all tuples that have for the key field the same "some:xx:" part, how can I archive this using JSON in an 'elegant' way?
The example you gave contains three different objects. So you can use javascript to look for text in a property.
obj1 = {"key":"some:xx:yy", "value": 72311};
if (obj1.key.indexOf("xx") !== -1) { // obj1.key contains "xx"
//do something
}
If you have an array with those values, then you can simply loop through the array and look for "xx" just like above for each element of array. And when found, you can assign that element to another array. So at the end of the loop, "another array" will contain all elements that contain "xx".
If you don't insist on using RegEx, i can show you an example code for the loop. If you insist on RegEx, let me know and i will help you.. just kidding, let me know and i will delete my answer and silently leave this question :)
I'm going to give you a straight answer to the question you asked, but hopefully the complexity and the raft of caveats will convince you that JSON.parse is a better alternative.
You can write a regular expression to match a single such tuple, but you can't write a regular expression to match all such tuples.
To explain why, consider the regular expression that matches one:
var stringBody = '(?:[^"\\\\]|\\\\.)*';
var string = '"' + stringBody + '"';
var space = '[ \t\r\n\f]*';
var colon = space + ':' + space;
var comma = space + ',' + space;
var uglyRegex = '^(?:[^"]|' + string + ')*?'
+ '"key"' + colon + '"(some:xx:' + stringBody + ')"' + comma
+ '"value"' + colon + '((?:[^\},"]|' + string + ')*)';
This works by finding the minimal number of non-string or full-string tokens that precede a key whose value starts with some:xx: and then looks for a value.
It leaves the key in matching group 1 and the value in matching group 2.
Since it has to match starting at the beginning to correctly identify string token boundaries, it cannot be used in a 'g' flag match.
Caveats
It assumes certain characters in "key"'s property value are not \uABCD escaped.
It assumes characters in the property names "key" and "value" are not \uABCD escaped.
It requires the key and value to occur in that order.
It cannot tell what other properties occur in the same object.
Each of these problems could be worked around by making the regex much more complex, but with regular expressions, often, the only way to handle a corner case is to make the regex much bigger.
When incremental improvements to code explode the size, the code is unmaintainable.
I want to add some strings to a textarea which are file basenames. Everything is fine, but the only problem is that it mixes all the values and there are not any line breaks:
var file_name = file.file_name;
var base = new String(file_name).substring(file_name.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1)
base = base.substring(0, base.lastIndexOf("."));
$('textarea#image_Basename').append(base).split('\n');
These are my file basenames:
5b0cd65710052633dc5dcac406a382c4
212asaddgcvjh622sdsds22113554dfd
5sd5weea55rr6qasfdjkloijhj665s6a
But after storing the data in to the database and retrieving it, the result I get is:
5b0cd65710052633dc5dcac406a382c4212asaddgcvjh622sdsds22113554dfd5sd5weea55rr6qasfdjkloijhj665s6a
To preserve newlines that are coming from a database or whatever, replace the newline characters with the HTML entity for a line feed:
base = base.replace("\n", '
');
$('#image_Basename').append(base);
If you're trying to append each string with a newline at the end, just concatenate it onto the string:
$('#image_Basename').append(base + '
');
Also, you're using split on the textarea jQuery element, which doesn't make sense as it is an object not a string.
My Special thanks to #rink.attendant.6, his second method worked for me :) The answer is:
$('#image_Basename').append(base + '
');
After adding this, I got all the file basenames in separate lines!
I simply have a huge array in a string like this:
"test", "blabla", "anothertest", "et", "cetera"
I need to be able to convert it to an array, preferable without the " "'s still left over.
I have no idea how javascript would be able to do this, but I heard JSON was able to do something like this.
JSON is fine indeed:
var string = '"test", "blabla", "anothertest", "et", "cetera"';
JSON.parse('[' + string + ']');
Keep in mind that string must respect the JSON syntax. More precisely, you have to check that double quotes are used, the separator is a comma and so on.
If your string contains data in quotes, and separated with comma, it almost valid json. Just do this
var myparsedarray = JSON.parse("[" + yourstring + "]");
Using Flickr API.
result.items[i].published
Results in something like this 2012-12-21T14:36:24Z - notice the T and the Z?
How do I match only the numbers in 2012-12-21T14:36:24Z?
This is how it looks.
newPic.innerHTML = "<div class='pic-container'> <p class='title'>" + result.items[i].title + "</p> <a href="+ result.items[i].link +" > <img src=\'" + result.items[i].media.m + "\'> </a></div><p class='author'>" + result.items[i].author.match(/\(([^)]*)\)/)[1] + "</p><p class='published'>" + result.items[i].published + "</p>";
You could use the RegExp matcher "\d" for this but I think a better solution would be to parse the Date with
var d = new Date(result.items[i].published)
From that you get a proper Date object.
you can use a simple regular expression like:
result.items[i].published.replace(/[a-z]/i , "");
or if you want to replace letters with spaces:
result.items[i].published.replace(/[a-z]/i , " ");
the two examples I provided will match ANY letter in your string and replace them, if you want to match more chars than just letters you can simply modify the regular expression.
Hope this answers your question,
Ignazio
Because the JS date object is hell to work with , the best solution is to run a simple REGEX replace to the string.
result.items[i].published.replace(/Z|T/gi," ")
If you need to work and do some advanced stuff with date i recommend to you the dateJS library.