jQuery?:( .tolowercase .replace text.match)在URL不可用时无效

时间:2017-04-09 07:52:32

标签: javascript jquery

我正在处理这个有效的greasemonkey脚本,除非没有URL。它是使除URL之外的所有内容都小写,然后替换所请求的内容。但是,这需要工作,即使DIV中没有URL,我真的不确定为什么它会像这样。

// ==UserScript==
// @name        twitter intent
// @namespace   covert
// @description twitter intent popupwindow text replace
// @include     https://twitter.com/intent/*
// @version     1
// @grant       none
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
// ==/UserScript==



$('#status').each(function() {
var text = $(this).text();
var n = text.indexOf('http');
var url = text.match(' http(s?):\/\/[^<\s]*');
text = text.replace(url[0],'');
text = text.toLowerCase()
.replace('climate change', '#climatechange')
.replace('climate ', '#climate ')
.replace('planet', '#planet')
.replace('ocean', '#ocean')
.replace('epa ', '#epa ')
text = text.slice(0,n) + url[0] + text.slice(n);
$(this).text(text);
});

这是一个有效的小提琴。只需删除HTML框中的网址,一切都开始停止工作: https://jsfiddle.net/qvsasvp2/

- 此代码取自:.tolowercase() only text except URL's?

1 个答案:

答案 0 :(得分:1)

只需将|| ''添加到包含正则表达式的行中:

var url = text.match(' http(s?):\/\/[^<\s]*') || '';

这可以确保字符串中没有匹配的URL(结果是假的,即null),将空字符串分配给url

请参阅更新的小提琴:https://jsfiddle.net/w7ocbhcd/1/