逃脱HTML和空白?

时间:2016-11-16 08:59:18

标签: javascript angularjs

用户输入保存在$scope.userInput中。我想检查用户是否在输入中输入了任何内容,但我想忽略空格和HTML标记,并仅检查其他类型的输入。

我该怎么做?

2 个答案:

答案 0 :(得分:1)


 
 var regex = /(<([^>] +)>)| \ s / ig;
 var string ="测试空格和< p> HTML标签< / p>";
 var result = string.replace(regex,"");
 的console.log(结果); // TestwhitespaceandHTMLtags
 
 

答案 1 :(得分:1)

// Input string
$scope.userInput = "<h1>My input</h1>";

// Removed HTML tags from the string.
var removedTagStr = $scope.userInput.replace(/(<([^>]+)>)/ig,'');

// Removed the white spaces from the string.
var result = removedTagStr.replace(/ /g,'');

console.log(result); // Myinput

正则表达式(<([^>]+)>)

的说明
----------------------------------------------------------------------
(                        group and capture to \1:
----------------------------------------------------------------------
<                        '<'
----------------------------------------------------------------------
(                        group and capture to \2:
----------------------------------------------------------------------
[^>]+                    any character except: '>' (1 or more
                         times (matching the most amount
                         possible))
----------------------------------------------------------------------
)                        end of \2
----------------------------------------------------------------------
>                        '>'
----------------------------------------------------------------------
)                        end of \1
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

工作演示:

&#13;
&#13;
var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    $scope.userInput = "<h1>My input</h1>";

var removedTagStr = $scope.userInput.replace(/(<([^>]+)>)/ig,'');

$scope.result = removedTagStr.replace(/ /g,'');

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  {{result}}
</div>
&#13;
&#13;
&#13;