[英]How can I loop through string and replace all periods except the last one?
Let's say I have a string like this: 假设我有一个像这样的字符串:
var test = my.long.file.name.zip
I am getting the total number of periods in this string with javascript like so: 我正在像这样用javascript获取此字符串中的句点总数:
var dots = (test.match(/\./g) || []).length;
I would then like to replace all of the periods in the string with underscores if there is more than one period in the string. 然后,如果字符串中有多个句点,我想用下划线替换字符串中的所有句点。
if(dots>"1"){
var newname = test.replace(/\./g, "_");
console.log(newname);
}
The problem is that this is replacing all of the periods. 问题在于这正在替换所有期间。 I would like to keep the last on intact.
我想保持最后一个完好无损。 So what I would like the
newname
variable to read as would be: 因此,我希望将
newname
变量读取为:
my_long_file_name.zip
My guess is that I should use $.each()
somehow to iterate over all except the last one to change the name. 我的猜测是我应该以某种方式使用
$.each()
遍历除最后一个更改名称之外的所有内容。 How should I do this? 我应该怎么做?
You dont necessarily need a loop, you could do it with a more complex regex, which uses a positive lookahead 您不一定需要循环,您可以使用更复杂的正则表达式来实现,它使用正向先行
The regex /\\.(?=.*\\.)/g
finds periods, but only where there is a subsequent period somewhere further along, which means the last one is not matched. 正则表达式
/\\.(?=.*\\.)/g
可以找到句点,但仅在/\\.(?=.*\\.)/g
地方有后续句点的地方,这意味着最后一个不匹配。
window.onload = function(){ var input = "my.long.file.name.zip" var result = input.replace(/\\.(?=.*\\.)/g,'_') alert(result); }
Consider splitting the string on '.'
考虑在
'.'
上分割字符串'.'
, then re-joining all but the last with '_'
: ,然后使用
'_'
重新加入除最后一个以外的所有内容:
var test = "my.long.file.name.zip"; parts = test.split('.'); var plen = parts.length; if (plen > 1) { test = parts.slice(0, plen - 1).join('_') + "." + parts[plen - 1]; } console.log(test);
a lookahead group in regex will work: 正则表达式中的超前组将起作用:
var test = 'my.long.file.name.zip'; var result = test.replace(/\\.(?=[^.]*\\.)/g, '_'); alert(result);
this matches a dot followed by ('anything but dot' and another dot), replacing only what is outside the group 这匹配一个点后跟(“除点之外的任何东西”和另一个点),仅替换组外的内容
var test = 'my.long.file.name.zip';
var last_index = test.lastIndexOf('.');
var newname = test;
if (-1 !== last_index) {
newname = test.replace(/\./g, '_');
newname = newname.substring(0, last_index).concat('.', newname.substring(last_index + 1));
}
console.log(newname);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.