在 Javascript 中从末尾修剪字符串
在 Javascript 中,如何将字符串从末尾修剪多个字符,追加另一个字符串,然后再次重新追加最初截断的字符串?
特别是,我有 filename.png
并想将其转换为 filename-thumbnail.png
。
我正在寻找类似的东西:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
.slice
,它接受负索引:用法:
You can use
.slice
, which accepts negative indexes:Usage:
尝试使用正则表达式(可以在 https://developer.mozilla.org 找到好的文档/en/JavaScript/Guide/Regular_Expressions)
我还没有测试过,但尝试如下:
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:
我将使用正则表达式来查找文件名的各个部分,然后根据需要重新排列并添加字符串。
像这样:
这会在 fileName 中给出文件名,在 fileExtension 中给出文件扩展名。从那里您可以添加或添加您想要的任何内容。
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:
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.
也许比正则表达式更简单,您可以使用lastindexof(请参阅http://www.w3schools.com/jsref /jsref_lastindexof.asp)来查找文件扩展名(查找句点 - 这允许更长的文件扩展名,例如 .html),然后按照 pimvdb 的建议使用切片。
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.
您可以使用正则表达式并执行如下操作:
rExtension
是一个正则表达式,用于查找扩展名,并将其捕获到$1
中。您会看到$1
出现在sAppend
内部,这意味着“将扩展名放在此处”。编辑:此解决方案适用于任何长度的任何文件扩展名。在这里查看它的实际效果:http://jsfiddle.net/h4Qsv/
You could use a regular expression and do something like this:
rExtension
is a regular expression which looks for the extension, capturing it into$1
. You'll see that$1
appears inside ofsAppend
, 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/