我正在尝试做类似于将url slug之类的变量转换为可用于标题的文本的操作。
因此,我有一个像这样的变量:
var thisID = 'athlete-profile';
function myFunc(thisID) {
// i need to use thisID as the id and href in a loop that generates a string of <li><a>'s\
function makeTitle(thisID) {
// convert thisID to text so for this example it would return 'Athlete Profile'
return 'Athlete Profile';
}
for () {
var str = '<li id="'+thisID+'"><a href="#'+thisId+'">'+makeTitle(thisID)+'</a>';
}
// make sense?
}
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我不想使用正则表达式来执行此操作,但是我不认为没有方法可以做到这一点。因此,任何知道如何做这类事情的人都会告诉我,这将是很大的帮助。
谢谢
Moo*_*oon 13
I would advise you to use regular expression. But if you really don't want to use regular expressions, the solution below would work for simple cases. Feel free to modify it as you like it.
function makeTitle(slug) {
var words = slug.split('-');
for (var i = 0; i < words.length; i++) {
var word = words[i];
words[i] = word.charAt(0).toUpperCase() + word.slice(1);
}
return words.join(' ');
}
console.log(
makeTitle("athlete-profile")
)Run Code Online (Sandbox Code Playgroud)
function titleize(slug) {
var words = slug.split("-");
return words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(' ');
}
Run Code Online (Sandbox Code Playgroud)
它的工作原理非常简单:
-分成单词。| 归档时间: |
|
| 查看次数: |
2839 次 |
| 最近记录: |