简体   繁体   English

JavaScript正则表达式三元字符串

[英]JavaScript Regex Ternary string

I'm using grunt usemin and filerev to versioned static assets along with uglify. 我正在使用grunt usemin和filerev与uglify一起对静态资产进行版本控制。

Things were working well for angular HTML template replacement in JS files until we ran into a case with if/else operators 在JS文件中替换角度HTML模板之前,一切工作都很好,直到遇到if / else运算符的情况

if($scope.isPdf){
    $scope.templateUrl = '/views/results/breakdown-detailed.html';
} else {
    $scope.templateUrl = '/views/results/breakdown.html';
}

converting things to a single line ternary operator after uglify 在uglify之后将其转换为单行三元运算符

$scope.templateUrl=$scope.isPdf?"/views/results/breakdown-detailed.html":"/views/results/breakdown.html"}}

Now the regex to target template strings for replacement no long capture all the html cases 现在,用于替换目标模板字符串的正则表达式不再捕获所有html案例

/templateUrl\s?[:=]\s?['"]([^"']+)["']/gm

Would anyone have a regex that would cover the ternary case of both values? 有人会使用正则表达式来覆盖这两个值的三进制情况吗?

If it could also cover the original case in a single regex that would be great. 如果它也可以在单个正则表达式中覆盖原始情况,那将是很好的。

$scope.templateUrl=$scope.isPdf?"/views/results/breakdown-detailed.html":"/views/results/breakdown.html"}} $ scope.templateUrl = $ scope.isPdf “/视图/结果/击穿detailed.html”:? “/视图/结果/ breakdown.html”}}

if($scope.isPdf){
    $scope.templateUrl = '/views/results/breakdown-detailed.html';
} else {
    $scope.templateUrl = '/views/results/breakdown.html';
}

I'll throw the test in regexr to try it out. 我将在regexr中进行测试以进行尝试。

Use the regex of the form 使用表格的正则表达式

templateUrl(([^?]*)\?([^:]*):([^;]*)|(\s*=\s*)[^;]*)

which would capture anything followed by a templateUrl 它将捕获任何内容,然后是templateUrl

For example see http://regex101.com/r/hD4wU7/1 on how the regex matches. 例如,有关正则表达式的匹配方式,请参见http://regex101.com/r/hD4wU7/1

Explanation 说明

  • templateUrl matches templateUrl templateUrltemplateUrl匹配

  • ([^?]*)\\?([^:]*):([^;]*) matches the ternary operator ([^?]*)\\?([^:]*):([^;]*)匹配三元运算符

    • ([^?]*)\\? matches anything other than ? 匹配什么? followed by question mark 跟问号

    • ([^:]*): matches anything other than : followed by : ([^:]*):匹配除:之后的所有其他字符:

    • ([^;]*) matches anything other than ; ([^;]*)匹配;

  • (\\s*=\\s*)[^;]*) matches the if case. (\\s*=\\s*)[^;]*)if大小写匹配。

    • (\\s*=\\s*) matches = (\\s*=\\s*)匹配=
    • [^;]*) matches anything other than ; [^;]*)匹配;

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

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