I am trying to get my path variable in this page to change the spaces and punctuation characters, as the user types it in. Here is the corresponding code:
<!doctype html>
<html lang="en-US" ng-app>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>ng-change</title>
<link rel="stylesheet" type="text/css" href="mystyle.css" media="all"/>
<script type="text/javascript" src="angular_1.0.7.js"></script>
</head>
<body>
<div class="browser" ng-controller="Browser">
<!--Mock browser URL-->
<div class="url">
← → ∞
<input type="text" value="edit/{{ path }}"/>
</div>
<!--Input field for the page, mock page-->
<div class="page">
<label for="update">
Update the URL:
<input ng-change="clean()" ng-model="path"/>
</label>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
However, when I type anything in, nothing happens. Here is the script.js file:
var Browser = function ($scope) {
$scope.clean = function () {
$scope.path = $scope.path
.replace("/\s+/g", "-")
.replace("/[^a-z0-9-]/i", "");
console.log($scope.path);
};
};
I am quite sure I've gotten my javaScript right, but I don't know why exactly my app is not working, I tried debugging it, the problem seems to be that ng-change
is only considering it a change when characters other than spaces are put in, whenever spaces are put in, it ignores them.
Your "regular expressions" are strings, not regular expression objects. The two ways to create a regex object are:
Remove the quotes from your code
.replace("/\s+/g", "-")
so they become.replace(/\s+/g, "-")
.The
.replace()
method does accept a string (as well as a regex), but attempts to find the first occurrence of that exact text instead of using the regex in the string.References:
.replace()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace