[英]how to add more text to a string before a special char
I would like to modify a string using jQuery as following: 我想使用jQuery修改字符串,如下所示:
Existing value: myimage_one.png
现有值: myimage_one.png
New value: myimage_one_notold.png
新值: myimage_one_notold.png
How can I do it? 我该怎么做? Maybe with the concat()
function? 也许使用concat()
函数?
You can use the replace()
function on your string. 您可以在字符串上使用replace()
函数。 In this case you could replace the .png
with _notold.png
: 在这种情况下,你可以更换.png
与_notold.png
:
var foo = 'myimage_one.png'; var bar = foo.replace('.png', '_notold.png'); console.log(bar);
Alternatively, you can use this regular expression if you want to only remove the last instance of the .
另外,如果您只想删除的最后一个实例,则可以使用此正则表达式.
, in cases where the filename contains more than one: ,如果文件名包含多个:
var foo = 'myimage_one.png'; var bar = foo.replace(/\\.([^\\.]*)$/,'_notold.$1'); console.log(bar);
Also note that both of the above use native JS methods and havenothing to do with jQuery 另请注意,以上两种方法均使用本机JS方法,与jQuery无关
function replaceString(org_str,replace_with)
{
var found_str = org_str.substring(org_str.lastIndexOf('.') + 1);
return org_str.replace(found_str, replace_with);
}
if you always want to append the string before the last .
如果您始终想将字符串附加在last之前.
you can use split: 您可以使用split:
http://www.w3schools.com/jsref/jsref_split.asp http://www.w3schools.com/jsref/jsref_split.asp
var strArr = existingVar.split('.');
var newString = "";
for (var i = 0; i < strArr.length; i++) {
if (i+1 < strArr.length) {
newString += strArr[i];
} else {
newString += "_notOld"+ strArr[i+1];
}
}
alert(newString);
this should do the job in every case, with each filetype and name (for example: my.new.file.is.cool.jpg
should work as well as myFile.png
or myImage.yeah.gif
) 这应该在每种情况下都可以完成,并使用每种文件类型和名称(例如: my.new.file.is.cool.jpg
以及myFile.png
或myImage.yeah.gif
)
假设您在文件名的最后一个点之后有任何字母,数字,下划线或破折号,然后:
filename = filename.replace(/(\\.[\\w\\d_-]+)$/i, '_notold$1');
You can do the changes using the following method, 您可以使用以下方法进行更改,
var existingVal = "myimage_one.png";
var modifiedVal = exisitingVal.replace(".","_notold.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.