Trimming a string from the end in Javascript - javascript

In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?
In particular, I have filename.png and want to turn it into filename-thumbnail.png.
I am looking for something along the lines of:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);

You can use .slice, which accepts negative indexes:
function insert(str, sub, pos) {
return str.slice(0, pos) + sub + str.slice(pos);
// "filename" + "-thumbnail" + ".png"
}
Usage:
insert("filename.png", "-thumbnail", -4); // insert at 4th from end

Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)
I haven't tested but try something like:
var re = /(.*)\.png$/;
var str = "filename.png";
var newstr = str.replace(re, "$1-thumbnail.png");
console.log(newstr);

I would use a regular expression to find the various parts of the filename and then rearrange and add strings as needed from there.
Something like this:
var file='filename.png';
var re1='((?:[a-z][a-z0-9_]*))';
var re2='.*?';
var re3='((?:[a-z][a-z0-9_]*))';
var p = new RegExp(re1+re2+re3,["i"]);
var m = p.exec(file);
if (m != null) {
var fileName=m[1];
var fileExtension=m[2];
}
That would give you your file's name in fileName and file's extension in fileExtension. From there you could append or prepend anything you want.
var newFile = fileName + '-thumbnail' + '.' + fileExtension;

Perhaps simpler than regular expressions, you could use lastindexof (see http://www.w3schools.com/jsref/jsref_lastindexof.asp) to find the file extension (look for the period - this allows for longer file extensions like .html), then use slice as suggested by pimvdb.

You could use a regular expression and do something like this:
var sImage = "filename.png";
var sAppend = "-thumbnail$1";
var rExtension = /(\.[\w\d]+)$/;
var sThumbnail = sImage.replace(rExtension, sAppend);
rExtension is a regular expression which looks for the extension, capturing it into $1. You'll see that $1 appears inside of sAppend, which means "put the extension here".
EDIT: This solution will work with any file extension of any length. See it in action here: http://jsfiddle.net/h4Qsv/

Related

How can I extract a part of this url with JavaScript?

I have an url that looks like this:
http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg
I want to extract hw6dNDBT.jpg, from the url above.
I tried playing around with regex patterns /img\/.*-/ but that
matches with img/hw6dNDBT-.
How can I do this in JavaScript?
try this:
var url = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
var filename = url.match(/img\/(.*)-[^.]+(\.[^.]+)/).slice(1).join('');
document.body.innerHTML = filename;
i would use split() method:
var str = "http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg";
var strArr = str.split("/");
var size = strArr.length - 1;
var needle = strArr[size].split("-");
var fileTypeArr = strArr[size].split(".");
var name = needle[0]+"."+fileTypeArr[fileTypeArr.length-1];
name should now be your searched String so far it contains no / inside it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
/[^\/]+$/ should match all characters after the last / in the URL, which seems to be what you want to match.
No regex:
//this is a hack that lets the anchor tag do some parsing for you
var parser = document.createElement('a');
parser.href = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
//optional if you know you can always trim the start of the path
var path = parser.pathname.replace('/assets/uploads/');
var parts = path.split('/');
var img = '';
for(var i=0; i<parts.length; i++) {
if (parts[i] == 'img') {
//since we know the .jpg always follows 'img/'
img = parts[i+1];
}
}
Ah, you were so close! You just need to take your regex and use a capturing group, and then add a littttle bit more!
img\/(.*)-.*(\..*)
So, you can use that in this manner:
var result = /img\/(.*)-.*(\..*)/.exec();
var filename = result[1] + result[2];
Honestly capturing the .jpg, is a little excessive, if you know they are all going to be JPG images, you can probably just take out the second half of the regex.
Incase you are wondering, why do we uses result[1] and result[2]? Because result[0] stores the entire match, which is what you were getting back. The captured groups, which is what we create when we use the parentheses, are stored as the indexes after 0.
Here is some one-liner:
var myUrl = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg',
myValue = myUrl.split('/').pop().replace(/-(?=\d).[^.]+/,'');
We take everything after the last slash then cut out the dimension part.

trim a string path using javascript

I have the following string:
var fileName = $(this).val();
this will give me a result:
C:\fakepath\audio_recording_47.wav
what I want is to obtain : audio_recording_47.wav
so, I need to trim it but I don't know how using javascript
please help
filename.split('\\').reverse()[0];
This will split the path by slashes, to obtain each part. Then to keep it simple, i reverse the array, so the last part that you need is now the first; and get the first part.
Or, even more simply: filename.split('\\').pop(), which will get the last item from the array.
You could write a little function to return the base name of the path:
function basename(fn) {
var x = fn.lastIndexOf("\\");
if (x >= 0) return fn.substr(x + 1);
return fn;
}
var filename = basename($(this).val());
You can do like this:
var fileName = $(this).val();
var path = fileName.split('\\');
var lastValue = path[path.length-1];
console.log(lastValue);//audio_recording_47.wav
Or, the shorter way you can do like this:
var fileName = $(this).val();
var path = fileName.split('\\').slice(-1);//audio_recording_47.wav
This should do it:
var trimmedFileName = fileName.match(/[^\\]*$/);
It matches everything that isn't a \ until the end of the string.
You could use a regular expression, like this:
var fileName = this.value.replace(/(?:[^\\\/]*[\\\/])*/, '');
Also, there is no need to use that snippet of jQuery, as this.value is both faster and simpler.

How to use split in javascript

I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij

delete specific part of a string and add another at the end

I have this span on my website with these values.
<span>1,4,4,7,5,9,10</span>
I want to use jquery to delete the "1," (or what ever the first number is) from the beginning of the string and add ",12" at the end (or any other number instead of 12) so it would look like this:
<span>4,4,7,5,9,10,12</span>
How can I do this with jquery or java script ?
<span id="myText">1,4,4,7,5,9,10</span>
JS:
var text = $('#myText').html().split(',').slice(1);
text.push('12');
$('#myText').html(text.join(','));
http://jsfiddle.net/samliew/RD6W8/7/
$('span').text(function(i, t) {
return t.replace(/\d+,/, '') + ',12';
})
http://jsfiddle.net/dnkEV/
You can use split or regular expressions with string.replace
Here's how to use split:
var arr = '1,4,4,7,5,9,10'.split(',');
arr.shift();
arr.push('12');
var result = arr.join(',');
Or with regular expressions (not a very readable one I concede):
'1,4,4,7,5,9,10'.replace(/^\d+,(.*)$/, '$1,12')
Using DOM API, you can do this:
var tn = span.firstChild;
tn.deleteData(0, tn.data.indexOf(",") + 1);
tn.data += ",12";
http://jsfiddle.net/KMzau/
Or like this:
var tn = span.firstChild;
tn.data = tn.data.slice(tn.data.indexOf(",") + 1) + ",12";

How do I remove part of a string from a url using JQuery?

How do I remove everything before /post in this string below and add my own address using Javascript/JQuery
showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
I want it to appear like this:
http://mydomain.com/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500
var str = 'showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500';
str = 'http://mydomain.com' + str.split('&dataFile=')[1];
Example: http://jsfiddle.net/52z2z/
Here it splits the string on '&dataFile=', gets the last item in the resulting Array, and concatenates it do your domain.
You could also do this in Javascript using regular expressions:
var url = "showLogo=false&showVersionInfo=false&dataFile=/post/2653785385/photoset_xml/tumblr_lepsihc2RV1qbclqg/500";
var matches = url.match(/dataFile=(.*)/);
var what_you_need = "http://mydomain.com" + matches[1];
HTH

Categories