JavaScript split string with backslash

百般思念 提交于 2021-02-17 07:17:09

问题


I get from server some path like that:

\some\some\some\some\mainSome

And for display it to front, I need only last path(mainSome).

And try to split it, but I can't.

 const path = '\some\some\some\some\mainSome'.split('\')
 //And also tried
 const path = '\some\some\some\some\mainSome'.split('\\')

And this didn't work.

Waiting for help from you


回答1:


try this

String.raw`\some\some\some\some\mainSome\`.split("\\");



回答2:


It's actually escaping the ss and ms in the string - you need to have a string with actual backslashes (escaped like \\):

const path = "\\some\\some\\some\\some\\mainSome".split("\\").pop();
console.log(path);



回答3:


If you are ok to add one more slash, it will work

 const path = '\\some\\some\\some\\some\\mainSome';
 const splitted = path.split('\\');

return the splitted variable gives you the array set.




回答4:


You need to escape backslashes (with backslashes) in your string too;

 const path = '\\some\\some\\some\\some\\mainSome'.split('\\');
 
 console.log(path);



回答5:


const url = 'some/some/some/mainsom';
const a = url.split('/');
const aGet = a[a.length-1];


来源:https://stackoverflow.com/questions/55450479/javascript-split-string-with-backslash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!