简体   繁体   中英

Javascript trim value before a specific character

I have a string like this.

var = "d:\\SJ\\filestore\\JMS\\Content\\input.cxml"

I need to trim the string before last \\\\ and get input.cxml

How can I do this in javascript?

Use substring() and lastIndexOf()

var a = "d:\\SJ\\filestore\\JMS\\Content\\input.cxml";
var result = a.substring(a.lastIndexOf("\\") + 1 );
console.log(result); // input.cxml
var path = "d:\\SJ\\filestore\\JMS\\Content\\input.cxml";
var splitString = path.split('\\');
var fileName = splitString[splitString.length-1];

You can use split() for that.

split() used on a string splits it into an array. In your example:

var path = "d:\\SJ\\filestore\\JMS\\Content\\input.cxml"
var pathArray = path.split("\\"); // [ "d:", "SJ", "filestore", "JMS", "Content", "input.cxml" ]

To extract the last element from an array just use .pop() .

You can do it by using .substring() and lastIndexOf()

var x = "d:\\SJ\\filestore\\JMS\\Content\\input.cxml";
var res = x.substring(x.lastIndexOf("\\") + 1);
console.log(res); //"input.cxml"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM