2016-11-16 54 views
0

用戶輸入保存在$scope.userInput。我想檢查用戶是否在輸入中輸入了任何內容,但我想忽略空格和HTML標記,並僅檢查其他類型的輸入。Escape html和whitespace?

我該怎麼做?

+0

'S /逃生/忽略/'...?你想*忽略*空白和HTML標籤...? – deceze

+0

是的,無視,我不知道正確的詞彙。我將編輯該問題。 – user1283776

+0

你的意思是你不想讓用戶通過按幾次空格來提交? – Crowes

回答

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 
---------------------------------------------------------------------- 

工作演示:

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,''); 
 

 
});
<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>

1

var regex = /(<([^>]+)>)|\s/ig; 
 
var string = "Test white space and <p>HTML tags</p>"; 
 
var result = string.replace(regex, ""); 
 
console.log(result); // TestwhitespaceandHTMLtags