简体   繁体   English

Javascript模式匹配和表达式评估逻辑

[英]Javascript pattern matching and expression evaluation logic

I have a javascript string which i want to evaluate as an expression and compare with values. 我有一个JavaScript字符串,我想将其评估为表达式并与值进行比较。

var stringExpression=">.5*{PropertyValue} + .2*{DesignValue}+ 2000 +{price}"; 

The values inside curly braces are of element id present in dom and the expression above is dynamic but the elements whose values i want to pick will always be present inside curly braces. 大括号内的值是dom中存在的元素id,上面的表达式是动态的,但我要选择其值的元素将始终出现在大括号内。 I plan to pick these values using jquery. 我计划使用jquery选择这些值。 $("#PropertyValue").val(). $(“#PropertyValue”)。val()。 Can somebody tell me how to do this evaluation in javascript post setting the values from dom and any ideas how to replace values, do i need to use split function or some regex can be used to achieve it. 有人可以告诉我如何在javascript中从dom设置值以及如何替换值的任何想法进行此评估,我是否需要使用split函数或可以使用某些正则表达式来实现它。

You can also point me to any framework in javascript that can help in this regards. 您也可以将我指向javascript中可以在这方面有所帮助的任何框架。

Thanks in advance. 提前致谢。

var str=">.5*{PropertyValue} + .2*{DesignValue}+ 2000 +{price}"; 

var regExp = /{(.*?)}/
var values = []
var match = str.match(regExp)
while (match != null) {
    var value = document.getElementById(match[1])
    str = str.replace(match[0], value)
    values.push(value)
    match = str.match(regExp)
}

Here is a solution in the functional paradigm which reads quite nicely: 这是功能范例中的一种解决方案,它的用法很不错:

function value(tag)
{
    var key = tag.substr(1, tag.length - 2) //remove braces
    return document.getElementById(key)
}


function populate(template)
{
    var tagRegExp = /{.+?}/g
    var tags = template.match(tagRegExp)
    var values = tags.map(value)
    return template.split(tagRegExp).zip(values).join("")
}

var template=">.5*{PropertyValue} + .2*{DesignValue}+ 2000 +{price}"; 
console.log(populate(template))

This solution requires a zip method for array objects which can be implemented as in the following (unless it is already provided by a library). 该解决方案需要用于数组对象的zip方法,该方法可以按以下方式实现(除非库已提供)。

Array.prototype.zip = function (other) {
    function zipOne(acc, x, i, a)
    {
        if (i < other.length) {
            if (i < a.length - 1) {
                return acc.concat([x, other[i]])
            } else {
                return acc.concat([x]).concat(other.slice(i))            
            }
        } else {
            return acc.concat([x])
        }
    }

    return this.reduce(zipOne, [])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM