0

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)

Community
  • 1
  • 1
user137717
  • 2,005
  • 4
  • 25
  • 48

2 Answers2

2

You need to use start anchor and quantifier * to match 0 or more characters until a / is found:

var regex = /^[^\/]*/
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • can you explain what the start anchor does and why the * comes after the exclusion clause? I would have thought you would build the pattern from the beginning up to the excluded character. – user137717 May 07 '15 at 17:06
  • Start anchor `^` is start of input and quantifier `*` is to match 0 or more characters before a `/` – anubhava May 07 '15 at 17:08
  • @user137717 depending on your circumstances you may want `/^[^/]+/` with `+` to match _**one** or more_ in place of `*` which matches _**zero**_ or more. – Stephen P May 07 '15 at 19:09
  • @StephenP good call Stephen P. I was getting some empty strings and used an if statement to work around, but that is very good to know. – user137717 May 07 '15 at 19:27
  • @user137717: Yes if you don't want empty string as a match then use `/^[^\/]+/`. Though for the given input even `/^[^\/]*/` will work. – anubhava May 07 '15 at 19:29
  • 1
    If it worked out, you may mark the answer as accepted by clicking on tick mark on top-left of my answer. – anubhava May 07 '15 at 19:36
1

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>
howderek
  • 2,224
  • 14
  • 23