[英]Splitting a complicated (?) string in javascript
我得到了这个字符串:
my.song.mp3 greatSong.flac not3.txt video.mp4 game.exe mov!e.mkv
我需要从文件类型中拆分文件名。
考虑到'.',我该怎么做? 像 .mp3 文件一样有问题吗?
从最后一次出现的 '.' 修剪它在字符串中。
let fileName = "my.song.mp3"; fileName = fileName.substring(0, fileName.lastIndexOf(".")) console.log(fileName)
编辑:刚刚意识到你可能是说这是一个大字符串,你需要返回一个文件名数组? 那正确吗? 如果是这样,这将起作用:
let initialString = "my.song.mp3 greatSong.flac not3.txt video.mp4 game.exe mov!e.mkv"; let fileNames = initialString.split(" "); fileNames = fileNames.map(fileName => fileName = fileName.substring(0, fileName.lastIndexOf("."))); console.log(fileNames);
function test()
{
try
{
// start with initial data
var theExample = "my.song.mp3 greatSong.flac not3.txt video.mp4 game.exe mov!e.mkv" ;
// split in individual file names by splitting string on whitespace
var fileNames = theExample.split(/\s/) ;
// run over each fileName
var i = fileNames.length ;
while (i-- > 0)
{
// remove literal dot and trailing word characters at the end of the string; show result
alert( fileNames[i].replace(/\.[\w]+$/,"") ) ;
}
}
catch(err)
{
// show error message
alert(err.message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.