Twitter在遇到特殊字符时停止引用

时间:2017-09-05 03:24:42

标签: javascript twitter

当我发推文时,如果引号包含特殊字符,例如“,”或:,则引号将以特殊字符前面的任何字符结尾。我使用.replace将一些特殊字符替换为文本版本,但有太多要替换。如何用常规文本替换所有html或unicode特殊字符?

CodePen:https://codepen.io/Wizikal/full/NvYvwz/

Javascipt Part:

$(document).ready(function(){
$('#newQuote').on('click', function(){
$.ajax({
  url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
  success: function(result){
    var post = result.shift();
    content = post.content;
    title = post.title;
    $('#quote').html(content);
    $('#author').html('~ ' + title);
  },
  cache: false,
})
})

$('#twitterShare').on('click', function(){
var newContent = content
.replace('<p>', '"')
.replace('<br>', ' ')
.replace('</br>', '')
.replace('</p>', '"')     
.replace('&#8216;', "'")
.replace('&#8217;', "'")
.replace('&#8220;', '"')
.replace('&#8221;', '"')
.replace('\u2019', "'")
.replace('&#39;', "'")
.replace('&#59;', ';')
.replace('&#45;', "-")
.replace('U+0027', "'")
.replace('&#1524;', '"')
.replace('U+201C', '"')
.replace('U+2018', "'")
.replace('U+2018', "'")
.replace('U+2019', "'")
.replace('&#1523;', "'")
.replace('U+003B', ';')
.replace('&#894;', ';')
.replace('U+037E', ';')
.replace('&#8228;', '.')
.replace('U+2024', '.')
.replace('&#8229;', '..')
.replace('U+2025', '..')
.replace('&#8230;', '...')
.replace('U+2028', '...')
.replace("'", "'")
.replace(';', ';')
.replace('&#38;', '&');

$(this).attr('href', 'https://twitter.com/intent/tweet?text=' + newContent  + ' ~ ' + title);
})

})

1 个答案:

答案 0 :(得分:0)

将引文传递给DOMParser,这会将html实体解码回正常的字符计数器部分。然后,您可以获取textContent以获取不包含html标签的字符串

content = (new DOMParser()).parseFromString(content,"text/html").documentElement.textContent;

由于您将引号放入$('#quote'),因此实体解码也在那里发生,因此您可以调用text()并获取相同的字符串(只要它是该元素中唯一的内容)

content = $('#quote').text();

演示

&#13;
&#13;
var content = "<p>Show me someone who has done something worthwhile, and I&#8217;ll show you someone who has overcome adversity.  </p>"
content = (new DOMParser()).parseFromString(content,"text/html").documentElement.textContent;

var link = document.createElement('a');
link.href = 'https://twitter.com/intent/tweet?text='+encodeURI(content);
link.innerText = "Right click & open in new tab";
link.target = "_blank";
document.body.appendChild(link);
&#13;
&#13;
&#13;