这里有一个函数,用于检查文本中是否有链接(如果有,则将其替换为可点击的链接)
示例:
该图像的实际分辨率是 3067x2276,而不是 4381x3251。请参阅this有关如何查找图像分辨率的信息页面。
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
if (matches.length > 2) {
var replace = `<a href="${matches[2]}">${matches[1]}</a>`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} else {
$("#text").append('<p>hello</p>');
}
});
}
<body>
<div class="container">
<div id="art" class="img column1">
</div>
<div id="text" class="comment column2">
</div>
</div>
</body>
我尝试在 Chrome 的 javascript 控制台上运行它,将 $("#text").append
... 替换为 console.log("hello")
,并且有用。为什么它在 jsfiddle 上不起作用?
最佳答案
使用 try 和 catch 代替
function getTopComment(permalink) {
var fullLink = "https://www.reddit.com" + permalink + ".json?sort=top";
$.getJSON(fullLink, function foo(result) {
var rawComment = result[1].data.children[0].data.body;
try {
var regExp = /\[(.*?)\]\(([^\)]+)\)/g;
var matches = regExp.exec(rawComment);
var replace = `<a href="${matches[2]}">${matches[1]}</a>`;
var cleanComment = rawComment.replace(matches[0], replace);
$("#text").append('<p>' + cleanComment + '</p>');
} catch(err) {
$("#text").append('<p>' + rawComment + '</p>');
}
});
}
关于javascript - 正则表达式 if else 语句失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53644762/