在点后添加空格但不在URL中添加空格

时间:2016-04-24 17:12:13

标签: javascript regex url

我有一个文字,其句子可能没有空格后像:

  

另见vadding.Constructions这个术语比比皆是。

如何在不在域名之前的点后添加空格?该文字可能包含以下网址:

  

另见vadding.Constructions这个术语比比皆是。 http://example.com/foo/bar

4 个答案:

答案 0 :(得分:4)

匹配并捕获一个URL,并匹配所有其他点以替换为点+空格:

var re = /((?:https?|ftps?):\/\/\S+)|\.(?!\s)/g; 
var str = 'See also vadding.Constructions on this term abound.\nSee also vadding.Constructions on this term abound. http://example.com/foo/bar';
var result = str.replace(re, function(m, g1) {
	return g1 ? g1 : ". ";
});
document.body.innerHTML = "<pre>" + result + "</pre>";

网址正则表达式 - (?:https?|ftps?):\/\/\S+ - 匹配httphttpsftpftps,然后是://和1 +非空格(\S+)。它是基本的一个,你可以使用一个你可以在SO上轻松找到的更复杂的一个。例如。见What is a good regular expression to match a URL?

更详细的方法

((?:https?|ftps?):\/\/\S+)|\.(?!\s)正则表达式有两种选择:网址匹配部分(如上所述)或(|)点匹配部分(\.(?!\s))。

请注意,(?!\s)是一个负向前瞻,它允许匹配一个未跟随空格的点。

当我们运行string.replace()时,我们可以指定一个匿名回调函数作为第二个参数,并将匹配和组参数传递给它。所以,在这里,我们有1个匹配值(m)和1个捕获组值g1(URL)。如果匹配了URL,则g1不为空。 return g1 ? g1 : ". ";表示我们不会修改第1组(如果匹配),如果不匹配,我们会匹配一个独立点,因此,我们会替换为.

答案 1 :(得分:0)

使用此模式:

/\.(?! )((?:ftp|http)[^ ]+)?/g

Online Demo

答案 2 :(得分:0)

如果没有后跟两个或三个小写字母或空格字符,您可以尝试使用RegExp /(\.)(?!=[a-z]{2}\/|[a-z]{3}\/|\s+|$)/g来匹配.字符

"See also vadding.Constructions on this term abound. http://example.com/foo/bar"
.replace(/(\.)(?!=[a-z]{2}\/|[a-z]{3}\/|\s+|$)/g, "$1 ")

答案 3 :(得分:0)

使用来自@MarcelKohls的想法

var text = "See also vadding.Constructions on this term abound. http://example.com/foo/bar";
var url_re = /(\bhttps?:\/\/(?:(?:(?!&[^;]+;)|(?=&amp;))[^\s"'<>\]\[)])+\b)/gi;
text = text.split(url_re).map(function(text) {
  if (text.match(url_re)) {
    return text;
  } else {
    return text.replace(/\.([^ ])/g, '. $1');
  }
}).join('');
document.body.innerHTML = '<pre>' + text + '</pre>';

相关问题