开发者

Need help with Javascript Replace Bookmarklet

I've searched the other questions and tried the suggestions but i still couldn't implement my bookmarklet successfully. Any suggestions on my code below will be appreciated. My goal is to get the script capture the current text selection via document.getSelection() and then replace all the dots with plus sign (it's for a task that has a few dots for each row of data).

javascript:(function(){ 

  var stringselect = null;

  function replaceString (text) {
    text = text.开发者_运维技巧replace('.','+');
    return text; 
  } 

  var stringselect = document.getSelection();
  var result = replaceString(stringselect);

  alert(result); //for testing purposes, i wanted to see the replaced text in the alert box but it didn't pop up.
})();


You haven't said how it doesn't work, but one thing jumps out at me:

text = text.replace('.','+');

That will only replace the first .. If you want to replace all of them, you have to use a regular expression rather than a string for the "find" argument, and you need to set the "global" flag on the regex:

text = text.replace(/\./g,'+');

(You need the backslash before the . because . is special in a regex, but you're actually looking for a real ., so we escape it.) The / delimit the regex literal, and the g is the "global" flag.

Separately: I think you mean window.getSelection, not document.getSelection, and note that IE doesn't support it until IE9. If you need to get text selections reliably cross-browser, you're in for some work. There's a handy library called rangy that can help.


Crossbrowser now

javascript:(function(){ var userSelection; if (window.getSelection) { userSelection = window.getSelection().toString();} else if (document.selection) { rng = document.selection.createRange(); userSelection =rng?rng.text:"ie borked"} var result = (userSelection)?userSelection.replace(/\./g,'+'):"Nothing replaced"; alert(result); })();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜