-4

I have a function like this:

function tweet(){
  window.open("https://twitter.com/intent/tweet?text=My text.  #myHashtag"
);
}

But JavasScript stops at the # sign. How to write it?

Radek John
  • 105
  • 8

3 Answers3

5

Use %23 which an encoded form of #.

If this is coming from the user, you really should use encodeURIComponent before putting it into the query string.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

Based on twitter doc, you can pass hashtags as &hashtags=

https://twitter.com/intent/tweet?text=My+text&hashtags=bransonpickel

https://dev.twitter.com/web/tweet-button/web-intent

Eddie
  • 26,593
  • 6
  • 36
  • 58
  • 1
    This is the right answer for Twitter specifically, but the other answers handle the more general case. – Barmar Feb 02 '18 at 17:17
  • @Barmar While I do prefer general case I also think solutions should use the tools provided with what they are working with. Would be great if the selected answer had both in it, the way twitter recommends and the way you can do it if you just encode the text, assuming that will work and tweet is properly hash-tagged doing so. – Nope Feb 02 '18 at 17:21
0

Encode the (input) text:

let input = "My text.  #myHashtag";
let baseUrl = "https://twitter.com/intent/tweet?text=";
// window.open(baseUrl + encodeURIComponent(input));
console.log(baseUrl + encodeURIComponent(input));
baao
  • 71,625
  • 17
  • 143
  • 203