I am trying to output the lines of a textfile to a div in an HTA. The text itself comes up just fine, however the lines do not carry over. Instead, the text is grouped together on one big line. If I print to a msgbox it comes up with correct, separated, lines.
function updateTPtally()
{
var fso, appdir, messagefile, ts, messagetext, line;
fso = new ActiveXObject("Scripting.FileSystemObject");
if (MESSAGE_FILE_NAME7.indexOf("\\") == -1) {
appdir = unescape(fso.GetParentFolderName(location.pathname));
messagefile = fso.BuildPath(appdir, MESSAGE_FILE_NAME7);
} else {
messagefile = MESSAGE_FILE_NAME7;
}
try {
// Open the message-of-the-day file as a TextStream.
ts = fso.OpenTextFile(messagefile, 1);
messagetext = "";
while (! ts.AtEndOfStream) {
line = ts.ReadLine();
// If the line contains text, enclose in <p> element;
// otherwise, construct a blank line with a nonbreaking space.
if (line.length > 0)
line = line.replace(/^(.*)$/, "$1");
else
line = "<p> </p>";
messagetext += line;
}
ts.Close();
}
// Construct an error message if an error occurred.
catch(err) {
messagetext = "<p>Can't display the message of the day.</p>"
+ "<p> </p>"
+ "<p>Error <b>0x" + hex(err.number) + "</b><br />"
+ err.description + "</p>";
}
// Update the innerHTML element of the textarea element with the
document.getElementById("TPtallymemo").innerHTML = messagetext;
}
EDIT:
I have added
line = line.replace(/\n/g, "");
This seems to work, however the first word of the text. This is my textfile:
Hello.
This should be line two. And written all in one line.
This should be line three, and also written on one line.
This is what prints out in my span:
Hello.
This
should be line two. And written all in one line.
This
should be line three, and also written on one line.
You are not enclosing the lines on the text after you replace them. Also, you shouldn't enclose the non-breaking space, as paragraph elements account to be correctly separated from each other.
Just one small final observation: you should call for AtEndOfStream() with the parentheses in your while condition.
messagetext = "";
while (! ts.AtEndOfStream()) {
line = ts.ReadLine();
// If the line contains text, enclose in <p> element;
// otherwise, construct a blank line with a nonbreaking space.
if (line.length > 0)
line = line.replace(/^(.*)$/, "<p>$1</p>");
messagetext += line;
}
Related
What i have done:
function makeBold(strings) {
var myHTML = document.getElementsByTagName('body')[0].innerHTML;
myHTML = myHTML.replace(strings, '<b>' + strings + '</b>');
document.getElementsByTagName('body')[0].innerHTML = myHTML
}
this code works only for the paces where the texts are free from ant tags
Eg: <p class="ClassName">Some free text without any inner html elements</p>
But for sentences below this the above javascript function is not giving any result
Eg sentence which are not working:
<p class="Aclass"><span class="char-style-override-1">Starting from here, </span><span class="char-style-override-2">text resumes after the span tag</span><span class="char-style-override-1">. again text resumes.</span></p>
What I need
i need a functionality to make the above text bold when i pass that text into my js function. and by text i mean only
Starting from here,text resumes after the span tag. again text resumes.
when i call the above mentioned jas function like this
makeBold('Starting from here,text resumes after the span tag. again text resumes.');
nothing happens, the entire sentence does not gets bold nothing happens, because the js function only looks for the occurrence of that string and makes it bold, in my second example the text is mixed with html tags
so that the above mentioned text will get bold when i call my makebold function.
Please note that i dont have the id for the <p> , what i have is a couple of random strings stored in my db and load a couple of webpages, while doing so i want to bold the sentence/text from the webpage if is matches with my passed string from db
While doing my research i got a code to highlight text given to a js. this js function will select the exact text in the html page which is passed to the js function.
the second eg also works for this code. i.e i can select the exact string from the example by passing it to the function.
function selectText(text) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.getElementById("button").blur();
document.execCommand("HiliteColor", false, "yellow");
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
textRange.collapse(false);
}
}
}
I tried to customize it so that instead of selecting the passed text, i tried to make it bold. but coudnt succed.
Please help me in getting this done. I am new to js.
I finally got a solution to your problem that works as you want it to (i. e. the function takes an arbitrary substring and marks anything that fits the substring bold while leaving the rest of the string untouched). If the string passed doesn't match any part of the string that you want to modify, the latter remains untouched.
Here goes (Beware: That JS section got really BIG!):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test case for making arbitrary text bold</title>
<meta charset="UTF-8">
<script type="application/javascript">
// Takes two strings and attempts to intersect them (i. e. the end of p_str1
// must match the beginning of p_str2). The index into p_str1 is returned.
// If no intersection can be found, -1 is returned.
function intersectStrings(p_str1, p_str2)
{
var l_pos = -1;
do
{
l_pos = p_str1.indexOf(p_str2[0], l_pos + 1);
if(p_str1.substr(l_pos) == p_str2.substr(0, p_str1.length - l_pos))
// If the two substrings match, we found something. Return with the position.
break;
}
while(l_pos != -1);
return l_pos;
}
function makeBold(p_string)
{
var l_elem = document.getElementById('modify');
var l_html = l_elem.innerHTML;
var l_text = l_elem.innerText;
var l_aux = l_html.match(/<.+?>/g);
var l_here = l_text.indexOf(p_string);
var l_before;
var l_middle;
var l_behind;
if(typeof(p_string) != 'string')
throw "invalid argument";
// First of all, see whether or not we have a match at all. If no, we don't
// need to continue with this.
if(l_here == -1)
{
console.error('makeBold: Could not find desired substring ' + p_string + '! Stop...');
return;
}
// Take the plain text and split it into three distinct parts (l_middle is of
// interest for us here).
l_before = l_html.slice(0, l_here);
l_behind = l_html.slice(l_here + l_html.length);
l_middle = l_html.slice(l_here, l_here + l_html.length);
if(l_aux)
{
// If we have a set of markup tags, we need to do some additional checks to
// avoid generating tag soup.
let l_target = new Array();
let l_tag;
let l_nexttag;
let l_this;
let l_endpos = 0;
let l_in_str = false;
let l_start;
while(l_aux.length - 1)
{
l_tag = l_aux.shift();
l_target.push(l_tag);
l_nexttag = l_aux[0];
l_endpos = l_html.indexOf(l_nexttag, 1);
l_this = l_html.slice(l_tag.length, l_endpos);
l_html = l_html.slice(l_endpos);
// Skip the entire rigmarole if there are two adjacent tags!
if(l_tag.length == l_endpos)
continue;
if(!l_in_str)
{
if((l_start = l_this.indexOf(p_string)) != -1)
{
// If we find the entire passed string in a fragment of plain text, we can
// modify that, reassemble everything and exit the loop.
l_before = l_this.slice(0, l_start);
l_behind = l_this.slice(l_start + p_string.length);
l_middle = l_this.slice(l_start, l_start + p_string.length);
l_this = l_before + '<strong>' + l_middle + '</strong>' + l_behind;
l_target.push(l_this);
l_target.push(l_html);
l_html = l_target.join('');
console.info('makeBold: The passed string fit between two tags: Done!');
break;
}
// Take the possibility of having to scan across fragments into account. If
// that is the case, we need to piece things together.
if((l_start = intersectStrings(l_this, p_string)) != -1)
{
// Once we wind up here we have a partial match. Now the piecework starts...
l_before = l_this.slice(0, l_start);
l_middle = l_this.slice(l_start);
l_this = l_before + '<strong>' + l_middle + '</strong>';
l_target.push(l_this);
console.info('makeBold: Found starting point of bold string!');
l_in_str = true;
}
else
{
// Nothing to do: Push the unmodified string.
l_target.push(l_this);
}
}
else
if((l_endpos = intersectStrings(p_string, l_this)) == -1)
{
// We haven't arrived at the end position yet: Push the entire segment with
// bold markers onto the stack.
l_this = '<strong>' + l_this + '</strong>';
l_target.push(l_this);
}
else
{
// We have an end position: Treat this fragment accordingly, wrap everything up
// and exit the loop.
l_behind = l_this.slice(l_endpos + 1);
l_middle = l_this.slice(0, l_endpos + 1);
l_this = '<strong>' + l_middle + '</strong>' + l_behind;
l_target.push(l_this);
l_target.push(l_html);
l_html = l_target.join('');
console.info('makeBold: Found the end part: Done!');
break;
}
}
}
else
l_html = l_before + '<strong>' + l_middle + '</strong>' + l_behind;
l_elem.innerHTML = l_html;
}
</script>
</head>
<body>
<header><h1>Test case for making arbitrary text bold by using JavaScript</h1></header>
<main>
<p id="modify"><span class="char-style-override-1">Starting from here, </span><span class="char-style-override-2">text resumes after the span tag</span><span class="char-style-override-1">. again text resumes.</span></p>
</main>
<script type="application/javascript">
// makeBold('Starting from here, text resumes after the span tag. again text resumes.');
// makeBold('from here, text resumes');
// makeBold('resumes after the span');
makeBold('text resumes after the span tag');
</script>
</body>
</html>
Unfortunately this job couldn't be done with a short section, because you need to take various cases into account that need to be handled individually. The control logic that I have come up with addresses all these concerns.
See the annotations in the JS that I have made for details.
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
[blog]: https://jsfiddle.net/kb413ae8/ "click here" for working fiddle
Kids Markers & Crayons is a response string for which highlighting of text should append, based on input we pass in searchQuery variable in code.
if Markers is provided as searchQuery input, Markers should be highlighted, which is currently working fine in above fiddle link.
if space is provided after word markers and pass has a searchQuery input in code, Kids 'b tag with class='boldTxt'>Markers & Crayons is appended. which is weird. Happens same for all word with space.
Highlight of text/word should happen if first character in searchQuery input matches with first character of word in response. does not matter where the word is. Thanks
var data = {"ResultSet":{"result":[
{"rank":"999999","term":"Kids Markers & Crayons"},
{"rank":"999999","term":"Crayola Fine Line Markers"},
{"rank":"999999","term":"Crayola Super Tips Washable Markers"},
{"rank":"999999","term":"Crayola Washable Markers Broad Line Classic"},
{"rank":"999999","term":"Post-it Assorted Page Markers"},
{"rank":"999999","term":"Crayola Markers Broad Line Classic"},
{"rank":"999999","term":"Crayola Crayons"},
{"rank":"999999","term":"Crayola Washable Markers Classic Colors"},
{"rank":"999999","term":"Crayola Washable Crayons Large"}]
,"totalResultsAvailable":"32","totalResultsReturned":11}};
for(i=0; i<9; i++) {
var result = data.ResultSet.result[i].term;
//console.log('result: ' + result);
var searchQuery = 'Markers ';
/*searchQuery inputs
searchQuery = 'c'; o/p: c should be highlighted at beginning of word, In classic 'c' is highlighting twice which should not be highlighted at end or in mid of word.
searchQuery = 'markers '; o/p: <b> tag is added which has to be removed.
searchQuery = 'markers & c '; o/p: <b> tag is added which has to be removed.
searchQuery = 'ola'; o/p: ola should be highlighted at beginning of word, In Crayola 'ola' is highlighting, which should not be highlighted at end or in mid of word.
*/
var searchResult = result;
words = searchQuery.split(' ');
$.each(words, function() {
var word = this.trim();
var regex = new RegExp('(' + word + ')(?!>|b>)', 'gi');
searchResult = searchResult.replace(regex, "<b class='boldTxt'>$1</b>");
});
console.log(searchResult);
$('#wag-typeaheadlists').append('<li><a>' + searchResult + '</a></li>')
}
.boldTxt {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul id="wag-typeaheadlists">
</ul>
In your fiddle try adding the following line after you split the searchQuery.
words = words.filter(function(word){ return word != "" });
Hope it solves your problem!
Im making a web page that, will get the html code of it self and then, replace all the harmful html codes like < and > and change them to the ascii counterparts so it doesn't skew it up but it looks write to the user also.
I need it to sperate the lines, by ether using the break line html code <br /> or some other way, I know how many lines I have by using themehtml.split("\n");
So the question is 'I need a way to add a line break at the end of the line'
This Is my most of my js code that kind of helps the question a bit
$(".edit_html_button").click(function()
{
var themehtml = $(".wrapper").html();
var oldhtml = _grubber_blog.html();
themehtml = themehtml.replace(/</g, "<"); //slowly removing html codes
themehtml = themehtml.replace(/>/g, ">"); //slowly removing html codes
themehtml = themehtml.split(' ').join(' ');//slowly removing html codes
themehtml = ("<div class='numberboxleft'></div><div class='edit_theme' contenteditable='true'>"+themehtml+"</div>");
themehtml = themehtml.split("\n");
//alert(themehtml);
_grubber_blog.css("background-color", "#fff");
$("#tiptip_holder").remove();
$("._grubber_blog_customize").html(" ");
$("._grubber_blog_customize").html(themehtml);
//adds the numbers up the left side
var e = 0;
var lenght = themehtml.length;
var numbers = "";
while (e < lenght){
numbers = $(".numberboxleft").html();
$(".numberboxleft").html(numbers + e + "<br />");
e++;
}
});
To replace newlines with html breaks you split on newlines and then join the array with html breaks:
themehtml.split("\n").join('<br>')
So I used the $.each function like so...
$.each(themehtml, function(){
var grad = $("._grubber_blog_customize").html();
$("._grubber_blog_customize").html(grad+this+"<br />");
});
This will gradualy add the striped html code to the div and make it look like its line by line
Please consider the following HTML <pre> element:
This is some
example code which
contains tabs
I would like to replace all of the tab characters with four non-breaking space characters in HTML (i.e. ). I have tested the above pre element with JavaScript for the presence of tab characters as follows:
$('pre').ready(function() {
alert(/\t/.test($(this).text()));
});
But it is always returned false. Can anyone tell me the correct process by which to replace tab spaces from the source code to HTML NBSPs? The tabs have been added by Komodo Edit, and are visible when viewing the source.
You can do it like this:
$('pre').html(function() {
return this.innerHTML.replace(/\t/g, ' ');
});
That will loop through all pre elements on the page and call the function for each of them. jQuery's html function uses the return value of the function we give to replace the content of each element. We're using String#replace to replace all (note the g flag on the regexp) tab characters in the HTML string with four non-breaking spaces.
Live example
It removes line breaks, extra spaces and line breaks:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
Demo:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
$('#acceptString').click(function() {
var str = prompt('enter string','');
if(str)
removeNewlines(str)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Enter String' id='acceptString' />
Try this:
var tab = RegExp("\\t", "g");
document.getElementById("text").value =
document.getElementById("text").value.replace(tab,' ');