I have this code:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script>
var TheSource;
$.ajax({
url: "http://www.domain.com/",
cache: false,
success: function(html){
TheSource = html;
TheSource = TheSource.substring(1,TheSource.indexOf("</head>"));
TheTitle = TheSource.substring(TheSource.indexOf("<title>")+7,TheSource.indexOf("</title>"));
alert(TheSource);
}
});
</script>
</head>
<body>
</body>
</html>
i get the part of the source i need from my site and i want to get from TheSource only the lines that start with var (i have several of them)
my questions are:
how do i break this returned html to lines?
how do i get everyline and check the beginning of it?
how do i remove indent of the script? (cause i have several lines with the var that begin with indent
Here's one way of doing it:
var TheSource = "var abcd; abcd; abcdabcd; var abcde ; var abcdef; \tvar abcd;\tvar;var;no var; \t no var;\nanother line;\nvar new line;";
var lines = TheSource.split(/;/); // get each line
var foundLines = new Array();
for (index in lines) {
var line = lines[index];
if (line.search(/^\s*var/)!=-1) { // look for "var" at the beginning of the string (ignoring whitespaces)
foundLines.push(line + ";"); //add a semicolon back
}
}
document.write(foundLines.join("<br>"));
Related
Good day, What I'm trying to do is to create a html table in jsp and modify the table with JQuery script(i reused a old, working script). The problem is i have never used JQuery nor web programming before but i have managed to compile a working version of the jsp which can generate a table but i couldn't make the JQuery script to execute.
My Simplified JSP :
<HEAD>
<script type="text/javascript" src="jquery-3.1.0.js"></script>
</HEAD>
<body>
<%
out.println("<table>");
out.println("<tr>");
out.println("<td>"+val_feature+"</td>");
out.println("<td>"+val_project+"</td>");
out.println("<td>"+val_suiteID+"</td>");
out.println("<td>"+val_suiteTitle+"</td>");
..............
..............
..............
out.println("</tr>");
out.println("</table>");
%>
<script type="text/javascript">
console.clear();
var table = $("table");
var rows = table.find($("tr"));
var colsLength = $(rows[0]).find($("td")).length;
var removeLater = new Array();
for(var i=0; i<colsLength; i++){
var startIndex = 0;
var lastIndex = 0;
var startText = $($(rows[0]).find("td")[i]).text();
for(var j=1; j<rows.length; j++){
var cRow =$(rows[j]);
var cCol = $(cRow.find("td")[i]);
var currentText = cCol.text();
if(currentText==startText){
cCol.css("background","gray");
console.log(cCol);
removeLater.push(cCol);
lastIndex=j;
}else{
var spanLength = lastIndex-startIndex;
if(spanLength>=1){
console.log(lastIndex+" - "+startIndex)
//console.log($($(rows[startIndex]).find("td")[i]))
$($(rows[startIndex]).find("td")[i]).attr("rowspan",spanLength+1);
}
lastIndex = j;
startIndex = j;
startText = currentText;
}
}
var spanLength = lastIndex-startIndex;
if(spanLength>=1){
console.log(lastIndex+" - "+startIndex)
//console.log($($(rows[startIndex]).find("td")[i]))
$($(rows[startIndex]).find("td")[i]).attr("rowspan",spanLength+1);
}
}
for(var i in removeLater){
$(removeLater[i]).remove();
}
</script>
</body>
When i execute the page the table is not modified by the JQuery and IE keeps throwing error 'console' undefined. I don't know if these problem related but when i remove the console.clear(), it still doesn't execute the script and throw 'Object is expected' error at 2nd line of the script var table = $("table");
Thanks in advance. Any suggestions would be much appreciated.
I'm developing a website and I need to break a word after "_".
For example, I have this "word":
test_test_test_test
And I want to break like this:
test_
test_
test_
test_
Is that possible?
Thanks.
I tried this, but didn't work:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var str = $('p').text();
var str_list = str.split("_");
for (var i = 0; i < str_list.length; i++) {
$('p').text(str_list[i] + "_");
}
});
</script>
</head>
<body>
<p>test_test_test_test</p>
<p>test2_test2_test2_test2</p>
</body>
</html>
'test_test_test_test'.match(/([a-z0-9]+_?)/gi)
the result is:
["test_", "test_", "test_", "test"]
You're looking for split.
var str = "test_test_test_test";
var str_list = str.split("_");
alert(str_list[0]);
If you want to print all of them then you need to iterate over the list.
for (var i = 0; i < str_list.length; i++) {
// I append the underscore to the end. Remove that bit if you don't want an underscore
alert(str_list[i] + "_");
}
var str ="test_test_test_test";
var parts=str.split('_');
parts.forEach(function(part){
alert(part+'_');
});
Here is another way to do it:
var words = word.replace(/_/g '_\0').split('\0');
The idea is to insert a marker after each _ and split on it. The marker should be a character that is not expected to appear in the actual data.
I have an HTML file that is using Javascript to do file I/O operations on a .txt file, via an ActiveXObject (only works in Internet Explorer, on Windows OS).
There is a text input box on the HTML page, and a button. The button calls a function onclick to write the text entered to the end of the .txt file. There is also a textarea on the HTML page, in which the modified contents of the .txt file are copied and pasted into. All of this is working so far...
So, I want to insert tabs and new-lines into the .txt file, from my HTML page with Javascript. I am using this line to copy the .txt file contents into the textarea, initialized in a variable:
var newText = oldText + "\n" + document.getElementById("userInput").value;
Of course, the escape character \n works on the HTML page, and not in the .txt file...
So how do I encode new lines, and tabs as well, into a parsable format for the .txt file? I have tried using the escape() method on ANSI values found here, and on ASCII values found here, but with no luck.
Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
</head>
<body>
<p>
Enter some text here:
<input type = "text" id = "userInput" />
</p>
<input type = "button" value = "submit" onclick = "main();" />
<br />
<hr />
<br /><br /><br />
<textarea id = "textHere" rows = 25 cols = 150></textarea>
<script type = "text/javascript">
// executes all code from this function to prevent global variables
function main()
{
var filePath = getThisFilePath();
var fileText = readFile(filePath);
writeFile(filePath, fileText);
} // end of function main
function getThisFilePath()
{
var path = document.location.pathname;
// getting rid of the first forward-slash, and ending at the last forward-slash to get rid of file-name
var correctPath = path.substr(1, path.lastIndexOf("/") );
var fixedPath = correctPath.replace(/%20/gi, " "); // replacing all space entities
return fixedPath;
} // end of function getThisFilePath
function readFile(folder)
{
var fso = "";
var ots = "";
var oldText = "";
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "read" mode (1)
ots = fso.OpenTextFile(folder + "writeToText.txt", 1, true);
oldText = ots.ReadAll();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
return oldText;
} // end of function readFile
function writeFile(folder, oldText)
{
var fso = "";
var ots = "";
var newText = oldText + "\n" + document.getElementById("userInput").value;
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "write" mode (2)
ots = fso.OpenTextFile(folder + "writeToText.txt", 2, true);
ots.Write(newText);
ots.Close();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
setText(newText); // with the function below
} // end of function writeFile
// called from the function writeFile
function setText(textFile)
{
document.getElementById("textHere").value = textFile;
} // end of function setText
</script> <!-- end of javascript -->
</body>
</html>
Windows expects "\r\n" as linebreaks. I'm quite sure you would find them in your textarea's value as well (after hitting enter). They will get automatically inserted when you set a value with "\n", and most libraries (like jQuery) do replace them with "normal" linebreaks when reading the value.
However, I would expect a file read/write with only "\n" to work, and when you load the file's text into your textarea they should show up. MS Notepad might have problems showing them.
var x=5
var char="Hi!
Is there any way to make JS write char x amount of times inside of an html element?
<span>Hyper guy wants to tell you
<script>
var x=5;
var char="Hi!;
document.write(char) and repeat x times;
</script>
</span>
The problem with using document.write is that it erases the whole page, so how would I insert it in context?
Use a loop that loops 5 times, each time adding 'Hi!' onto the end.
var x = 5;
var char = '';
while (x--) {
char += 'Hi!';
}
// write once
document.write(char);
Or, you can just write 5 times:
var x = 5;
var char = 'Hi!';
while (x--) {
document.write(char);
}
Up to you which you choose, though I'd prefer the first (the less you mess with the document, the better).
try this:
<span>Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var c="Hi!"; //close the quotes.
for (;x>=0;--x)
document.write(c);
</script>
</span>
document.write(..) doesnt erase the content of the entire page, if it is used in a proper way.
Really? I'm not sure where you got the idea that it erases the page first.
When I execute the following in FF3, after adding the missing closing quote following Hi!:
<html>
<head></head>
<body>
<span>
Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var chars="Hi! ";
var i;
for (i = 0; i < x; i++) document.write(chars);
</script>
</span>
</body>
</html>
I get:
Hyper guy wants to tell you Hi! Hi! Hi! Hi! Hi!
Create a HTML element in the page where you want to insert text
Use document.getElementById to get the element and append the text to element using .innerHTML .text property to it
http://www.tizag.com/javascriptT/javascript-innerHTML.php
example:
//add this empty span in the HTML page
<span id="newText"></span>
<script type="text/javascript">
var x=5, count;
var char='Hi!', resultString = '';
for(count=0;count<x;count++)
{
resultString = resultString + char;
}
document.getElementById('newText').innerHTML = resultString;
</script>
I'm running the following code. The button basically adds a chart into the html page. The problem I'm facing is: when I click on the button for the second time, the curve of the former chart fades away (though the labels don't), and I want it to stay. I've tried to debug and this happens when I modify the innerHTML property right at the beginning of the buttonClicked javascript function. Can anybody tell me why is this happening?
<html>
<head>
<title>Configurando gráficos</title>
<script language="javascript" type="text/javascript" src="../scripts/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../scripts/jquery.flot.js"></script>
<script type="text/javascript" language="javascript">
var id = 0;
function requestGraph(placeholder) {
$.ajax({url: "../requests/get_xml_oid.php?oid=1.3.6.1.2.1.2.2.1.10.65540&host=200.234.199.161", success: function(request){
// Initialize dataToDraw to an empty array
var dataToDraw = [];
// The first tag is called ifInOctets
var ifInOctetsEl = request.getElementsByTagName("ifInOctets")[0];
// Store the data element, to loop over the time-value pairs
var dataEl = ifInOctetsEl.getElementsByTagName("data");
// For each data element, except the first one
var i;
for (i=1; i<dataEl.length; i++){
// get the time-value pair
var timeEl = dataEl[i].getElementsByTagName("time")[0];
var valueEl = dataEl[i].getElementsByTagName("value")[0];
var time = timeEl.textContent;
var value = valueEl.textContent;
// get the value of the former data element
// Warning: the former value in the XML file is newer than the latter
var formerValueEl = dataEl[i-1].getElementsByTagName("value")[0];
var formerValue = formerValueEl.textContent;
// push to the dataToDraw array
dataToDraw.push( [parseInt(time)*1000, parseInt(formerValue) - parseInt(value)]);
}
// tell the chart that the x axis is a time variable
var options = {
xaxis: { mode: "time"}
};
// plot the chart and place it into the placeholder
jQuery.plot(jQuery(placeholder), [dataToDraw], options);
}});
}
function buttonClicked() {
document.getElementById("body").innerHTML += "<div id=\"placeholder" + id + "\" style=\"width:600px;height:300px;\"></div>";
requestGraph("#placeholder" + id);
setInterval("requestGraph(\"#placeholder" + id + "\")",60000);
id = id + 1;
}
</script>
</head>
<body id="body">
<button type="button" onClick="buttonClicked()">Click Me!</button>
</body>
</html>
According to this previous question, assigning to innerHTML destroys child elements. It's not clear to me that this is exactly what you're seeing, but perhaps using document.createElement as suggested in the similar question will work for you as well.