javascript 替换某个点之前的所有文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10568815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all text before a certain point
提问by UserIsCorrupt
$(function(){
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
var replaced = alphabet.replace(/(M).+$/,'');
$('body').text(replaced);
});
How can I make this go in the opposite direction, replacing M
and everything before it?
我怎样才能让它朝着相反的方向发展,替换M
它之前的一切?
回答by VisioN
Use /^.+M/
expression:
使用/^.+M/
表达式:
$(function() {
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
var replaced = alphabet.replace(/^.+M/,'');
$('body').text(replaced);
});
DEMO:http://jsfiddle.net/kbZhU/1/
演示:http : //jsfiddle.net/kbZhU/1/
The faster option is to use indexOf
and substring
methods:
$(function(){
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
var replaced = alphabet.substring(alphabet.indexOf("M") + 1);
$('body').text(replaced);
});
DEMO:http://jsfiddle.net/kbZhU/2/?
演示:http : //jsfiddle.net/kbZhU/2/?
回答by morex87
回答by Will
FYI if you are trying to do this with more than one letter, you have to change it a bit.
仅供参考,如果您尝试使用多个字母来执行此操作,则必须对其进行一些更改。
Using @VisioN solution I was trying to replace anything in a URL up to a certain point.
使用@VisioN 解决方案,我试图在某个特定点替换 URL 中的任何内容。
So to get everything after 'google.com' in https://www.google.com/analytics
, I had to do
所以为了在 'google.com' 之后获得所有内容https://www.google.com/analytics
,我必须这样做
const url = 'https://www.google.com/analytics'
const lookingFor = 'google.com'
const replaced = url.substring(url.indexOf(lookingFor) + lookingFor.length)
replaced
will then return /analytics
replaced
然后会回来 /analytics