What will be the JavaScript template to match any given string?

I need to make sure that this line is not "Choose a value." To do this, everything else must match the pattern except this exact string.

I looked around and tried many combinations at http://www.regular-expressions.info/javascriptexample.html , but nothing like the trick.

I canโ€™t deny the test, the template has to do it all, since I will feed this to the extent of checking the form. If the selection contains this text, I will return an error, etc. So the pattern should match anything other than this exact line,

I tried a lot of things (?! Select an account)! (Choose an account)! (^ (Select account) $)

etc ... I donโ€™t understand how some of these mechanisms work. I get "starts with" and "ends with", but it seems I have not found a simple negation operator.

For some reason, everywhere I seek explanations for regular expression. I do not get this simple use case, it may not be common.

How can i do this?

Thanks!

+4
source share
4 answers

I believe this asked something like this:

Regular expressions and negation of a whole group of characters

In your case, you can use something like

^(?!Select a value).*$ 

That will match all that does NOT begin with "Choose a value."

+10
source

Instead of thinking about a negative regex, make a positive and negate condition:

 if (! /^Select an account$/.test(mystring)) { // String is not "Select an account" } 

But for this you do not need a regular expression:

 if (mystring != 'Select an account') { // String is not "Select an account" } 

Or if you want "contains":

 if (mystring.indexOf('Select an account') == -1) { // String does not contain "Select an account" } 
+2
source

Perhaps I do not understand this correctly. Would it work?

 if (string != "Select a value") { //code here } 

I do not know why you need regular expressions, so I am afraid that I do not understand what your question is.

0
source

An additional solution, if you are working with a regular expression in HTML5 form, and the pattern attribute of your input is more complex than one exact line, it looks like this (javascript):

 function findAllNotPattern(inputField) { var allBut1 = inputField.getAttribute("pattern") var allBut2 = allBut1.slice(0, 1) + "^" + allBut1.slice(1) var allButRe = new RegExp(allBut2, "g") return allButRe } 

if you want to run it in pure javascript you should use:

 findAllNotPattern(document.getElementById("inputFieldId")) 
0
source

All Articles