简体   繁体   中英

How to cut a string after X apparition of a specific character in javascript?

I have a string that looks lite that : str = "aaaa-050-xxx-zzz"

I need to cut my string after the second '-' So in this example, i want to get "aaaa-050"

The number of characters before and after each '-' isn't constant.

Then i need to remove the '-' in the new string to get "aaaa050"

What's the best way to do that ?

You have several choices. Aside from just looping through the string looking for the second - , there are both regex and String#split solutions:

With a regular expression, you can find the first two segments without - in them separated by a - and then use them to form the replacement:

 var str = "aaaa-050-xxx-zzz"; str = str.replace(/^([^-]*)-([^-]*)-.*$/, '$1$2'); console.log(str); 

Or there's a split solution where you split on - and then join the first and second segments:

 var str = "aaaa-050-xxx-zzz"; var parts = str.split("-"); str = parts[0] + parts[1]; console.log(str); 

If this structure is your pattern, you can split by - and join the parts:

 var str = "aaaa-050-xxx-zzz"; var splited = str.split("-"); var res = splited[0] + "-" + splited[1]; console.log(res); 

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