Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, January 14, 2007

Javascript selecting text with bookmarklet example

Here is a example of selecting text in Javascript. I've create a bookmarklet that let you search a word in dictionary.com. Just remove tabs and newline.

javascript:(
function(){
var str="";
if(window.getSelection){
str=window.getSelection();
} else if(document.getSelection){
str=document.getSelection();
} else if(document.selection){
str=document.selection.createRange().text;
}
var d=window.open("http://dictionary.reference.com/" +
"search?q="+str,"dictionary","1");
window.setTimeout(function(){d.focus()},300);
}
)()

Saturday, January 13, 2007

Javascript string replace

Didn't know Javascript had regular expression support.

    var str = "abcabc";
str.replace("a", "#");
document.write( str );
will print "abcabc".
    var str = "abcabc";
document.write( str.replace("a", "#") );
will print "#bcabc".
    var str = "abcabc";
document.write( str.replace(/a/g, "#") );
will print "#bc#bc".
    var str = "ABCABC";
document.write( str.replace(/a/i, "#") );
will print "#BCABC".
    var str = "ABCABC";
document.write( str.replace(/a/gi, "#") );
will print "#BC#BC".