regex if else语句失败



这里有一个函数,用于检查文本中是否有链接(如果有,则将其替换为可点击的链接(

示例:

此图像的实际分辨率为3067x2276,而不是4381x3251。有关如何找出图像分辨率的信息,请参阅本页。

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-and-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>');
}
});
}
如果正则表达式与结果不匹配,则exec返回null。先检查一下。
...
if (matches && matches.length > 2) {
...

最新更新