.tolowercase()只有文字除了URL?

我一直在为Greasemonkey编写这个脚本。 问题是.tolowercase()显然它将大小写为小写,这会破坏URL。 我已经研究过.startswith()和.endswith()作为可能的解决方案,例如以http和https开头; 也许前缀检测一些’http *’? 无论如何,这是下面的代码,提前感谢:

// ==UserScript== // @name twitter intent // @namespace random // @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(); $(this).text(text.toLowerCase() .replace('... ', ' ... ') .replace('health ', '#health ') .replace('video', 'Video') .replace('emergency', '#emergency') .replace('climate change', '#climatechange') .replace('climate ', '#climate ') ); }); 

这是在代码运行之前的HTML。

  

编辑:重要的是除了url之外的文本是大写或小写被忽略但仍然是.replace文本,如果检测到他们自己的单词。

所以我尝试了结合位置,url并重新附加它。

这最终是这样的:

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

尝试将文本解析为URL,如果有效,请不要小写它:

你可以看到它在我制作的小提琴中起作用 – https://jsfiddle.net/y1jh5w0w/

 text = text.split(' '); text.forEach(function (value, index) { try { var url = new URL(value); } catch (ex) { text[index] = value.toLowerCase(); } }); text = text.join(' '); 

为什么不能使用正则表达式来查找某些字符串是从https://http:// ,然后不要在其上应用toLowerCase

 const regex = /^(https:\/\/)/g; const str = `https://www.FaceBook.com`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 
 var dictionary1= { " A":" b", " B":" b", " C":" C", }; jQuery(document).ready(function() { setTimeout(function() { $("#status").each( function(){ for( var ptrn in dictionary1){ $(this).text( $(this).text().replace(new RegExp(ptrn ,"g"), dictionary1[ptrn] ) ); } }); }, 100); });