当我发推文时,如果引号包含特殊字符,例如“,”或:,则引号将以特殊字符前面的任何字符结尾。我使用.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('‘', "'")
.replace('’', "'")
.replace('“', '"')
.replace('”', '"')
.replace('\u2019', "'")
.replace(''', "'")
.replace(';', ';')
.replace('-', "-")
.replace('U+0027', "'")
.replace('״', '"')
.replace('U+201C', '"')
.replace('U+2018', "'")
.replace('U+2018', "'")
.replace('U+2019', "'")
.replace('׳', "'")
.replace('U+003B', ';')
.replace(';', ';')
.replace('U+037E', ';')
.replace('․', '.')
.replace('U+2024', '.')
.replace('‥', '..')
.replace('U+2025', '..')
.replace('…', '...')
.replace('U+2028', '...')
.replace("'", "'")
.replace(';', ';')
.replace('&', '&');
$(this).attr('href', 'https://twitter.com/intent/tweet?text=' + newContent + ' ~ ' + title);
})
})
答案 0 :(得分:0)
将引文传递给DOMParser,这会将html实体解码回正常的字符计数器部分。然后,您可以获取textContent以获取不包含html标签的字符串
content = (new DOMParser()).parseFromString(content,"text/html").documentElement.textContent;
由于您将引号放入$('#quote')
,因此实体解码也在那里发生,因此您可以调用text()
并获取相同的字符串(只要它是该元素中唯一的内容)
content = $('#quote').text();
演示
var content = "<p>Show me someone who has done something worthwhile, and I’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;