1

I want to check with JavaScript & Regex that a test only validates any kind of string between pipes |

So these will test true

`word|a phrase|word with number 1|word with symbol?`
`word|another word`

But any of these will say false

`|word`
`word|`
`word|another|`
`word`

I have tried this

const string = 'word|another word|'
// Trying to exclude pipe from beginning and end only
const expresion = /[^\|](.*?)(\|)(.*?)*[^$/|]/g
// But this test only gives false for the first pipe at the end not the second
console.log(expresion.test(string))
1
  • sounds like a .split("|") job to me.. Commented Nov 22, 2020 at 13:46

1 Answer 1

2

The pattern [^\|](.*?)(\|)(.*?)*[^$/|] matches at least a single | but the . can match any character, and can also match another |

Note that this part [^$/|] mean any char except $ / |


You can start the match matching any character except a | or a newline.

Then repeat at least 1 or more times matching a | followed by again any character except a |

^[^|\r\n]+(?:\|[^|\r\n]+)+$

Explanation

  • ^ Start of string
  • [^|\r\n]+ Negated character class, match 1+ times any char except | or a newline
  • (?: Non capture group
    • \|[^|\r\n]+ Match | followed by 1+ times any char except a | or newline
  • )+ Close group and repeat 1+ times to match at least a single pipe
  • $ End of string

REgex demo

const pattern = /^[^|\r\n]+(?:\|[^|\r\n]+)+$/;
[
  "word|a phrase|word with number 1|word with symbol?",
  "word|another word",
  "|word",
  "word|",
  "word|another|",
  "word"
].forEach(s => console.log(`${pattern.test(s)} => ${s}`));

If there will be no newlines present, you can use:

^[^|]+(?:\|[^|]+)+$
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it does work, however it will never be a new line, it was just an example of different combinations, it will always be a single line string

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.