在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);
}
}

最新更新