使用Javascript删除字符串中的所有URL

时间:2018-01-28 11:15:06

标签: javascript node.js twitter

如何使用Javascript删除字符串中的所有网址,无论它们出现在何处?

例如,对于以下推文 -

ExpressionBuilder

我想回来

Initialise

5 个答案:

答案 0 :(得分:0)

如果你的网址不包含文字空格,你可以使用正则表达式https?.*?(?= |$)将http与可选的s匹配到下一个空格或字符串的结尾:

var str = '...Ready For It?" (@BloodPop ® Remix) out now -  https://example.com/rsKdAQzd2q';
str = str.replace(/https?.*?(?= |$)/g, "");
console.log(str);

或拆分空格并检查部分是否以“http”开头,如果是,则删除它们。

var string = "...Ready For It?\" (@BloodPop ® Remix) out now -  https://example.com/rsKdAQzd2q";
string = string.split(" ");

for (var i = 0; i < string.length; i++) {
  if (string[i].substring(0, 4) === "http") {
    string.splice(i, 1);
  }
}
console.log(string.join(" "));

答案 1 :(得分:0)

首先,你可以用空格分割它

var givenText = '...Ready For It?" https://example2.com/rsKdAQzd2q (@BloodPop ® Remix) out now -  https://example.com/rsKdAQzd2q'
var allWords = givenText.split(' ');

您可以使用自己的实现来过滤掉非网址单词以检查网址,这里我们可以检查索引://为简单起见

    var allNonUrls = allWords.filter(function(s){ return 
      s.indexOf('://')===-1 // you can call custom predicate here
  });

所以非URL字符串将是:

var outputText = allNonUrls.join(' ');
// "...Ready For It?" (@BloodPop ® Remix) out now - "

答案 2 :(得分:0)

您可以在字符串上使用正则表达式替换来执行此操作,但是,找到匹配所有URL的良好表达式是不方便的。但是有点像:

label_binarizer.classes_

使用正确的正则表达式是许多StackOverflow问题的主题,它取决于您是否只需匹配http(s)://xxx.yyy.zzz或更一般的模式,如www.xxx.yyy 。

要使用正则表达式模式,请参阅此问题:What is the best regular expression to check if a string is a valid URL?

答案 3 :(得分:0)

function removeUrl(input) {
            let regex = /http[%\?#\[\]@!\$&'\(\)\*\+,;=:~_\.-:\/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789]*/; 
            let result = input.replace(regex, '');
            return result;
}

let result = removeUrl('abc http://helloWorld" sdfsewr');

答案 4 :(得分:0)

要从字符串中删除所有网址,您可以使用正则表达式来标识字符串中的所有网址,然后使用String.prototype.replace将所有网址替换为空字符。

这是John Grubber's Regex,可用于匹配所有网址。

/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/g

因此,要替换所有网址,只需使用上述正则表达式替换

let originalString = '"...Ready For It?" (@BloodPop ® Remix) out now -  https://example.com/rsKdAQzd2q'
let newString = originalString.replace(/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/g,'')
console.log(newString)