函数生成字符串
function to make string CamelCase
我需要一个函数,使字符串camelcase仅使用javascript。我想让它不包含split
之类的内置函数。请附上解释。
如果我有"dean john"我想把它改成"dean john"。
var myString = "Hello world!";
var myArray = [];
var out= ""
for (var i=0; i < myString.length; i++){
myArray.push(myString[i]);
//myArray.pop(myString[i]);
myArray[0].toUpperCase();
}
alert(myArray)
所需输出:H 嗨 W ,
我不想使用split或任何其他内置函数
使用regex:
str.replace(/(^ *| +)(.)/g, function(v,p1,p2){return p1+p2.toUpperCase()})
使用for循环,你可以这样做:
var u=true, r=''
for(var i=0; i < str.length; i++){
c=str[i]
r+=u?c.toUpperCase():c
u=(c==' ')
}
如果要显示为HTML,可以使用CSS
.capitalize-all-words {
text-transform: capitalize;
}
在你的视图
<span class='capitalize-all-words'>hello world</span>
还有一种方法,使用边界:'b
' b匹配零宽度的单词边界,例如在字母和空格之间。(不要与['b]混淆)
例如,/'bno/匹配"at noon"中的"no";/ly'b/匹配"possibly yesterday"中的"ly"
所以regex可以像这样
myString.replace(/'b('w)/g,function(m,p1){ return p1.toUpperCase();})
希望这对你有帮助!
String.prototype.toTitleCase = function(){
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?'.?|via)$/i;
return this.replace(/[A-Za-z0-9'u00C0-'u00FF]+[^'s-]*/g, function(match, index, title){
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
title.charAt(index - 1).search(/[^'s-]/) < 0) {
return match.toLowerCase();
}
if (match.substr(1).search(/[A-Z]|'../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
document.getElementById("rawText").innerHTML = document.getElementById("rawText").innerHTML.toTitleCase();
<div id="rawText">sdfdsfsd sdfsdf awwads</div>
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- jQuery中是否内置了任何字符串格式化函数
- JavaScript按钮/输入/函数,字符串反转
- 推荐在JavaScript中执行存储为字符串的函数,而不是使用eval
- 编辑输出字符串函数ol.control.MouseControl
- 如何在 Javascript 和 qUnit 中模拟字符串函数
- 如何在for()语句中执行字符串函数
- GulpJS:对SVG文件内容执行字符串函数
- 在干净的字符串函数之间添加空格
- 错误将导致最长重复子字符串函数
- Javascript:替换在IE7-8中不工作的字符串函数
- 如何使用拆分字符串函数的结果在Angular.js中进行排序
- 反转不工作的字符串函数
- 在Python中,你可以像在JavaScript中那样创建字符串函数的原型
- 我如何使用简单的子字符串函数在javascript标题大小写句子
- Javascript字符串函数
- 来自字符串函数的图像
- 有没有任何方法可以在不使用javascript子字符串函数或regex的情况下生成这个字符串日期表示(带时区)
- 在从CFC返回结果之前,对AJAX查询执行字符串函数
- 不能调用下划线.字符串函数' lpad '用于错误'未捕获的类型错误:_.Lpad不是一个函数