Conditional Renderings with JavaScript Regex

拥有回忆 提交于 2019-12-01 09:31:38

I'd suggest an expression like this:

/^if\s+([\w\s]+)\s+equals\s+"([\w\s]*)"\s+then\s+(\w*)$/

Which you could use like this:

var expression = // set this to your input
var matches = expression.match(/^if\s+([\w\s]+)\s+equals\s+"([\w\s]*)"\s+then\s+(\w*)$/);

if (matches) { // if matches isn't null
    // matches[1] is the field name
    // matches[2] is the value in quotes
    // matches[3] is the operation to perform

I haven't hardcoded "Hide" and "Show" into the regex - instead it returns whatever string is after "then". I figured that would make it easier to add more operations later. If you want to hardcode these operation names just change the final (\w*) to (Hide|Show). Also this expression will work if the part in quotes is an empty string, which may be valid for some field values.

Demo: http://jsfiddle.net/2UFHN/1/

Note: You said _"any number of digits, and/or letters and/or white-spaces" - for that you just need [\w\s]+. In your expressions you had (\d*|\w*)\s+, which means "zero or more digits OR zero or more word characters FOLLOWED BY by one or more spaces". \w already matches digits (as well as a-z and underscore), so you don't need \d as well.

You might want to add an i flag to your expression, as in /expressionhere/i to make it case insensitve.

Just use "; no need to escape it.

Also, you're apparently trying to match the " without first matching the equals, so it won't match any of your test cases.

/^if\s+(\d*|\w*)\s+".*$/.test("if abc \"xyz\"") // ==> true
/^if\s+(\d*|\w*)\s+".*$/.test("if abc equals \"xyz\"") // ==> false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!