简体   繁体   中英

regex to match ALL characters up to a certain marker

I'm trying to write a regex to match all characters up to a '/' My current regex only matches the first character of the string

var regex = /[^\/]/
regex.exec("something/15")

This will give me 's'. I have also tried

var regex = /.*[^\/]/

but it returns the whole string undelimited by '/'. I have taken a look at this other SO post as well.

Javascript regular expression: match anything up until something (if there it exists)

您需要使用起始锚和量词*来匹配0个或多个字符,直到找到/为止:

var regex = /^[^\/]*/

Although this can be accomplished with a RegEx, I would recommend using String.split() to accomplish this.

I imagine you may also want the text following the slash, so the split would allow you to access it more easily

 var str = 'First value/second value'; document.getElementById('output').innerHTML = str.split('/')[0]; 
 <div id="output"></div> 

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