Home > Web Front-end > JS Tutorial > body text

JS application regular expression case conversion example_javascript skills

WBOY
Release: 2016-05-16 16:36:05
Original
1625 people have browsed it

js中应用正则表达式转换大小写,代码很简单,看代码:

以下首字母大写,其它字母小写

<script type="text/javascript"> 
function replaceReg(reg,str){ 
str = str.toLowerCase(); 
return str.replace(reg,function(m){return m.toUpperCase()}) 
} 
var reg = /\b(\w)|\s(\w)/g; 
var str = 'share javascript'; 
var str2 = 'SHARE JAVASCRIPT'; 
var str3 = 'Test \n str is no good!'; 
var str4 = 'final test'; 
document.write(replaceReg(reg,str)+'<br />'); 
document.write(replaceReg(reg,str2)+'<br />'); 
document.write(replaceReg(reg,str3)+'<br />'); 
document.write(replaceReg(reg,str4)+'<br />'); 
</script>
Copy after login

以下只首字母大写,其它字母大小写不作处理

<script language="JavaScript"> 
<!-- 
var str="xi nAn shi you xUe yuan china people" 
alert(str.replace(/\s[a-z]/g,function($1){return $1.toLocaleUpperCase()}).replace(/^[a- 
z]/,function($1){return $1.toLocaleUpperCase()})) 
//--> 
</script>
Copy after login

运行代码,直接看效果就可以了!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template