简体   繁体   中英

Split string JavaScript in a specific way

Hi I want to split a string in a specific way in javascript, like if the string is C:/users/Me/AppData/elastic/elastic 1.6. I know I can split it using the split() method and use pop() and shift() to get first and last splitted string but I want to split it like, except the last string. So the answer should be like “C:/users/Me/AppData/elastic"

I did it like this,

str.split(str.split("/").pop()).shift()

I got the out put like this,

C:/users/Me/AppData/

But I want it like this,

C:/users/Me/AppData

It sounds like you're saying that you want the final item in the path to be dropped. To do that, you can use .lastIndexOf() to get the last / position, and then .slice() up to that point if it wasn't -1 .

 var str = "C:/users/Me/AppData/elastic/elastic 1.6"; var idx = str.lastIndexOf("/"); var res = str; if (idx !== -1) { res = str.slice(0, idx); } console.log(res); 

Or like this, which is similar to your attempt, but may be slower:

 var str = "C:/users/Me/AppData/elastic/elastic 1.6"; var res = str.split("/"); res.pop(); res = res.join("/"); console.log(res); 

Your original solution does work as long as the last item doesn't appear anywhere else in the URL. Otherwise you'll get only the part before the first split item.

If you want regex:

var str = "C:/users/Me/AppData/elastic/elastic 1.6"; 
str = str.replace(/\/[^\/]*$/, "");

The expression reads:

  1. Grab everything starting from / until the end of the string.
  2. There should be no / in between.
  3. Replace it with nothing

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