473,382 Members | 1,814 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

return character position on page?

Is there a way to return the character position on a page? Not the x
and y coordinates, but the number of characters on a page. For
instance i have a html page with the following text: This is my string.
Then character postion for m would be 9. Any thoughts?

Jul 23 '05 #1
5 2305
je*********@hotmail.com wrote:
Is there a way to return the character position on a page? Not the x
and y coordinates, but the number of characters on a page. For
instance i have a html page with the following text: This is my string.
Then character postion for m would be 9.


What a strange request:-)

To answer straightly, yes you can do it, first by retrieving the text of
the document, then by searching the chars within the text.

You have many ways to retrieve the text:
- documents are represented by trees of nodes (elements), which kind of
mirror the structure of your HTML page. What you can do is therefore to
identify the "text" elements, retrieve their value and concatenate all
values;
- some browsers (IE, Opera) offer an "innerText" property, which
directly gives the text contained in an element;
- some browsers (IE, Mozilla) support "text ranges", which are also a
good way to get the text from nodes.

Once you've retrieved the text you just have to apply string methods or
regular expressions to find your chars, but you won't be able to do much
afterwards (like highlighting or whatever).

Just out of curiosity, why do you exactly need the positions? Given the
structure of the DOM I cannot really think of a practical application.
<div>Hello, World!</div>
<div>This is my string</div>

<form action="">
<input type="text">
<input
type="button"
value="getCharPosition()"
onclick="alert(getCharPosition(this.form.elements[0].value));">
</form>

<script type="text/javascript">
var getCharPosition = (function(){
function getTextFromNode(node){
if(typeof node.innerText!="undefined") return node.innerText;
else
return function(N){
for(var ii=0, s="", c=N.childNodes;ii<c.length;ii++) {
if(c[ii].nodeType==3) s+=c[ii].nodeValue;
else if(
c[ii].nodeType==1 &&
c[ii].nodeName.toLowerCase()!="script"
) s+=arguments.callee(c[ii]);
}
return s;
}(node);
}

return function(token) {
if(
token.length>0 &&
document.body && (
typeof document.body.innerText!="undefined" ||
document.body.childNodes &&
document.body.nodeName
)
){
var txt=getTextFromNode(document.body).replace(/\r|\n/g,"");
var match;
var re=new RegExp(token, "gi");
var positions=[];
while((match=re.exec(txt))!=null) {
positions[positions.length]=match.index+1;
}
return positions.length==0 ?
"No char found." :
"Char(s) found at " + positions.join(" - ");
} else {
return "Cannot find char position!";
}
}
})();
</script>
HTH,
Yep.
Jul 23 '05 #2
I am using it to store what a users selects or highlights within a html
page. That position plus the length of the highlight will then be
passed to an application to be stored so that when they revisit the
page, what the user selected will still be highlighted. The app needs
the postion on the page, as well as the length of the highlight.

Jul 23 '05 #3
Lee
je*********@hotmail.com said:

I am using it to store what a users selects or highlights within a html
page. That position plus the length of the highlight will then be
passed to an application to be stored so that when they revisit the
page, what the user selected will still be highlighted. The app needs
the postion on the page, as well as the length of the highlight.


And you're absolutely sure the page contents will never change?
Nobody will ever correct a typo, throwing off the character count?

Jul 23 '05 #4

Yes is doable, but to recall it once the page is gone from an object is
another matter, unless the hierarchy is kept intact, which may not be, but
the object you want for that is a Range object, make a Range object off
the selection, store to cookie with escaped() chars and all, and when the
page is visited again, check for the cookie and run a string query on
document.body childNodes. Mozilla and IE and Opera do Ranges.
Danny
On Thu, 09 Jun 2005 13:33:52 -0700, <je*********@hotmail.com> wrote:
Is there a way to return the character position on a page? Not the x
and y coordinates, but the number of characters on a page. For
instance i have a html page with the following text: This is my string.
Then character postion for m would be 9. Any thoughts?


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 23 '05 #5
Yep
je*********@hotmail.com wrote:

Hi,
I am using it to store what a users selects or highlights within a html
page. That position plus the length of the highlight will then be
passed to an application to be stored so that when they revisit the
page, what the user selected will still be highlighted. The app needs
the postion on the page, as well as the length of the highlight.


I'm starting to see what you want, however I'm afraid you won't be be
able to do it the way you want, given the way the page is parsed
client-side: basically you manipulate nodes, not text.

What I can suggest is the following: capture the user selection, alter
the tree, store the altered tree in a DB with the username, and send
the altered tree back when requested by the user. The code below should
work in IE/Mozilla (slightly tested only, I'm on my way to holidays).

Given the nature fo the text to be highlighted, then you might consider
sending only a part of the tree, or even adopt a text-based highlight
(is there's no more than 1 occurrence of the text in your page - you
still don't tell the "real" why:-)).
---
<script type="text/javascript">
var SelectionManager = (function() {
var MARKER_CLASS="markerClass";

function getSel(){
var sel=null;
if(
typeof document.selection!="undefined" &&
document.selection &&
document.selection.type=="Text"
){
sel=document.selection;
} else if(
window.getSelection &&
window.getSelection().rangeCount>0
){
sel=window.getSelection();
}
return sel;
}

function createRange(){
var rng=null;
if(document.body && document.body.createTextRange) {
rng=document.body.createTextRange();
} else if(document.createRange) {
rng=document.createRange();
}
return rng;
}

function moveRange(rng, el){
var moved=false;
if(rng.moveToElementText){
rng.moveToElementText(el);
moved=true;
} else if(rng.selectNodeContents) {
rng.selectNodeContents(el);
moved=true;
}
return moved;
}

function selectRange(rng){
if(rng.select){
rng.select();
} else if(window.getSelection) {
var sel=window.getSelection();
if(sel && sel.removeAllRanges && sel.addRange) {
sel.removeAllRanges();
sel.addRange(rng);
}
}
}

function createRangeFromSel(sel){
var rng=null;
if(sel.createRange) {
rng=sel.createRange();
} else if(sel.getRangeAt) {
rng=sel.getRangeAt(0);
if(rng.toString()=="") rng=null;
}
return rng;
}

function markRange(rng){
var marked=false;
if(rng.pasteHTML){
rng.pasteHTML(
"<span class='"+MARKER_CLASS+"'>"+rng.text+"<\/span>"
);
marked=true;
} else if(rng.extractContents){
var span=document.createElement("span");
span.className=MARKER_CLASS;
span.appendChild(rng.extractContents());
rng.insertNode(span);
marked=true;
}
return marked;
}

function createSelectionFromNode(node){
var rng=createRange();
if(rng){
if(moveRange(rng, node)){
selectRange(rng);
}
}
}

document.onmouseup = function(evt){
var sel=getSel(), rng;
if(sel) {
rng=createRangeFromSel(sel);
if(rng) {
SelectionManager.lastSelection=rng;
}
}
}

return {
lastSelection : null,
markLastSelection : function() {
return this.lastSelection && markRange(this.lastSelection);
},
highlightSelection : function() {
if(document.getElementsByTagName){
var span=document.getElementsByTagName("span");
for(var ii=span.length; ii--;) {
if(span[ii].className.indexOf(MARKER_CLASS)!=-1) {
createSelectionFromNode(span[ii]);
break;
}
}
}
}
};
})();

function submitHandler(frm){
frm.elements['SelectionInfo'].value=
SelectionManager.markLastSelection()?document.body .innerHTML:"";
return true;
}

window.onload = function(evt){
SelectionManager.highlightSelection();
}
</script>

<div>Hello, World!</div>

<form action="foo" onsubmit="return submitHandler(this)">
<input type="hidden" name="SelectionInfo">
<input type="submit" value="Send selection">
</form>
---
HTH,
Yep.

Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Noah | last post by:
I have a text field in a form. I want the user to be able to click a DELETE button and have the character at the cursor position deleted. This would be just as if the user had pressed the Back...
9
by: MSUTech | last post by:
Hello, What is the best way to check each character within a string? For doing something like encryption, where you check character 1 and replace it with a different character.. then check...
1
by: Colin Green | last post by:
OK here's is what I wish to do. I have an XML file that I want to read into an XmlDocument. I then want to be able to interrogate the XmlNodes to find both their start AND end character positions...
1
by: King Kong | last post by:
we are facing this kind of error when we double click the infragistic web grid please help me on this Regards Moid Iqbal Server Error in '/NetworkAccess' Application....
5
by: Just D | last post by:
All, Any valuable idea about subj: "The '%' character, hexadecimal value 0x25" ? I tried to google, but nothing interesting was found. Is it IIS settings problem, user side problem or...
7
by: =?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7z | last post by:
Who could explain the follow issue ? ¦¤ Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'gbk' codec can't encode character u'\x80' in position 0: il...
2
by: thuythu | last post by:
Please help me.... I used and Javascript to view the data. But when i click button open a popup windows, then select data and click save button. The popup close and return the main page, but the...
3
by: magix | last post by:
How can I search for occurance of a character in certain position of a string I checked function strchr, but doesn't option to specify position. Thanks. Regards, Magix
5
by: Andrus | last post by:
I use Winforms RichTextBox control to edit scripts. Scripts are plain ascii texts. When error occurs, script engine returns character position of error in code as integer. How to position...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.