运用正则+replace+substring将一段英语的字母大写 angurlar运用自定义指令filter完成首字母大写...

本文介绍了一种使用JavaScript结合正则表达式、replace及substring方法实现字符串首字母大写的技巧,并展示了如何通过AngularJS自定义指令应用此功能。

复习下js基础并运用正则+replace+substring将一段英语的字母大写

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首字母大写</title>
</head>
<body>
<div class="dv"></div>
</body>
</html>
<script>
var str = "this is a javascript string";
str = str.replace(/\b\w+\b/g,function(word){ //运用正则方式将语句截取成一个一个的单词
console.log(word);//打印出来截取的字符串
console.log(word.substring(0,1).toUpperCase())//将截取的首字母大写
console.log(word.substring(0,1).toUpperCase()+word.substring(1)) //将大写的字符串拼接到未大写的上面
return word.substring(0,1).toUpperCase()+word.substring(1);//将所有的字符return出去
})
document.write(str)//在页面上打印出来
</script>

配合angularjs 的自定义指令将命令输出

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>

</head>
<style>
input.ng-invalid{
background: red;
}
</style>
<body>
<div ng-app="myApp" ng-init='firstName="Jon"' ng-controller="mycrl">

<input type="text" ng-model="name" required/>
<h2>年龄:{{age}}</h2>
{{ str | toUpercase}} //输出结果
</div>
</body>
</html>

<script src="js/angurlar素材/angular/angular.js"></script>
<script>


var app =angular.module("myApp",[]);
app.controller("mycrl",function($scope){
$scope.name="";
$scope.age =18;
$scope.str= "this is my first work"
});
app.filter("toUpercase",function(){//自定义指令
return function(str){
return str.replace(/\b\w+\b/g,function(word){//replace配合正则截取每一个单词
return word.substring(0,1).toUpperCase()+word.substring(1);//运用substring截取每个单词的首字母并大写
});

}
})
</script>

这样就输出个简单的angular应用了

转载于:https://www.cnblogs.com/a8497336/p/6745503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值