tags:

views:

91

answers:

3

I found some code using google search:

function insertAtCaret (textarea, icon) { 
    if (document.getElementById(textarea).createTextRange && document.getElementById(textarea).caretPos) { 
            var caretPos = document.getElementById(textarea).caretPos; 
            selectedtext = caretPos.text; 
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '' ? icon + '' : icon;//this line I am not understand
}
}

function storeCaret (textarea) { 
    if (document.getElementById(textarea).createTextRange) document.getElementById(textarea).caretPos = document.selection.createRange().duplicate(); 
}

here why need judge

caretPos.text.charAt(caretPos.text.length - 1) == ''

I think icon+'' and icon are equal

A: 

icon + '' is guaranteed to be of type string. icon may not be.

EDIT: I have no idea why it's checking whether the charAt is an empty string and basing its decision to cast icon to a string on that, though.

Alan
Agreed, this is the only result I could come up with as well, but I have no clue why it would use the inline conditional to determine whether we need to cast icon to string or just use as is. From the check itself it seems it wouldn't matter and the check is erroneous.
Dustin Fineout
A: 

'' intended to be not empty string but single space character. In IE if you double click the word then it is selected and also the space character that follows the word also is selected. So now if you paste some text (icon) in place of your selection then selected text together with the space will be replaced - so you loose the space after pasting.

That is the reason why a space is added to the pasted text - in order to not loose space if it was selected together with some word. But if no space was selected then we do not add a space to an inserted word.

This script is very popular on the different kinds of the forums for text formatting.

Svitlana Maksymchuk
In that case either the paste is faulty (the string added to `icon` IS empty) or MSIE universally interprets the empty string as a single space character.
Alan
:) no no no, string added to 'icon' should not be empty it should be a space :)... maybe space was lost somewhere during formatting?
Svitlana Maksymchuk
it is not a space, it's indeed a empty stringsee in http://bit.ly/9GZ5c
yjfuk
A: 

If '' is actually a single space (misrepresented here due to formatting), then I think your explanation is correct: Google is working around IE's behavior of including the trailing space when a whole word is selected. Since the pasted icon is going to replace the selection, Google wants to restore that trailing space.

But then I'm not sure what the original question is about. Clearly icon+' ' and icon are not equal; one has an extra space. Right?

Paul A Jungwirth