Reputation: 51
I would like to modify a string using jQuery as following:
Existing value: myimage_one.png
New value: myimage_one_notold.png
How can I do it? Maybe with the concat()
function?
Upvotes: 0
Views: 101
Reputation: 337560
You can use the replace()
function on your string. In this case you could replace the .png
with _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
Upvotes: 1
Reputation: 41
You can do the changes using the following method,
var existingVal = "myimage_one.png";
var modifiedVal = exisitingVal.replace(".","_notold.");
Upvotes: 0
Reputation: 3800
function replaceString(org_str,replace_with)
{
var found_str = org_str.substring(org_str.lastIndexOf('.') + 1);
return org_str.replace(found_str, replace_with);
}
Upvotes: 1
Reputation: 117
Lets assume you have any series of letters, numbers, underscore or dash after the last dot in the file name, then:
filename = filename.replace(/(\.[\w\d_-]+)$/i, '_notold$1');
Upvotes: 0
Reputation: 5629
if you always want to append the string before the last .
you can use split:
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
)
Upvotes: 0