0

I am trying to write a regexp (javascript) to validate a string where slashes are repeated.

Must be:

/ - valid string

/abs - valid string

/abs/ - valid string

/abs/a - valid string

// - invalid string

//asd//sd/ -invalid string

/as//a - invalid string

a/a - invalid string

abs - invalid string

////////sdf///// - invalid string

I am trying this regexp:

(\/){1}[\w-]*
^(\/){1}[\w-]*
^(\/\w+)+(\.)?\w+(\?(\w+=[\w\d]+(&\w+=[\w\d]+)*)+){0,1}$

How do I write an expression to pass the validation criteria?

4
  • You don't need regex for such a simple task. If I understood your examples correctly, the input string is invalid if it contains two consecutive slashes. Use String.includes() to find if the input string contains the substring '//'. Commented Aug 10, 2020 at 16:37
  • It doesn't work for me. Validation occurs with a field on the form that is not available to me. I can just set the validation parameters. In this case, a regular expression Commented Aug 10, 2020 at 16:43
  • If I could I would just do it - "////asd///sd//".replace(/\/+/g, '/') Commented Aug 10, 2020 at 16:45
  • Why are "a/a" and "abs" invalid? You need define "valid". I suggest you add a sentence such as the following after your first sentence: "A string is valid if it meets the following conditions:...". Your first sentence needs to be clarified, as you are not validating strings containing repeated forward slashes. Commented Aug 10, 2020 at 17:41

1 Answer 1

1

This is a pretty simple regex and should work for any engine:

^\/[^\/]+(?:\/[^\/]+)*$

The idea is that it should always start with a forward slash and no two forward slashes should touch. You can test it here: https://regex101.com/r/1BCQs3/2/

Sign up to request clarification or add additional context in comments.

2 Comments

This assumes (perhaps correctly) that strings that do not begin with a forward slash are invalid. That is consistent with the examples given in the question but was not stated as a requirement of valid strings. You therefore should make that assumption explicit. Easier would be ^(?!.*\/\/)\/.
@CarySwoveland Nice! This works for my examples. Thank!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.