使用 JavaScript 将字符串转换为标题大小写

发布于 2024-07-07 21:55:43 字数 229 浏览 7 评论 0 原文

有没有一种简单的方法将字符串转换为标题大小写? 例如,john smith 变为 John Smith。 我并不是在寻找像 John Resig 的解决方案 这样的复杂内容,只是(希望如此) )某种单线或两线。

Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

怪我鬧 2024-07-14 21:55:44

如果您可以在代码中使用第三方库,那么 lodash 为我们提供了一个辅助函数。

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'

If you can use third party libraries in your code then lodash has a helper function for us.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'

狼性发作 2024-07-14 21:55:44

ES 6

str.split(' ')
   .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
   .join(' ')

其他

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')

ES 6

str.split(' ')
   .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
   .join(' ')

else

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')
愛上了 2024-07-14 21:55:44
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

似乎有效...
使用上述内容进行测试,“快棕色的狐狸?/jumps/ ^over^ the ¡lazy!dog...”和“C:/program files/somevendor/他们的第二个应用程序/a file1.txt”。

如果您想要 2Nd 而不是 2nd,可以更改为 /([az])(\w*)/g

第一种形式可以简化为:

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

Seems to work...
Tested with the above, "the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog..." and "C:/program files/some vendor/their 2nd application/a file1.txt".

If you want 2Nd instead of 2nd, you can change to /([a-z])(\w*)/g.

The first form can be simplified as:

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
战皆罪 2024-07-14 21:55:44

试试这个最短的方法:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());

Try this, shortest way:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
往日 2024-07-14 21:55:44

吉姆·鲍勃 -> 吉姆-鲍勃吉姆

/鲍勃-> 吉姆/鲍勃

jim_bob -> Jim_Bob

不是 -> 不是

école -> 麦当劳学校

-> 麦当劳

function toTitleCase(str) {
  return str.replace(/\p{L}+('\p{L}+)?/gu, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.slice(1)
  })
}

jim-bob -> Jim-Bob

jim/bob -> Jim/Bob

jim_bob -> Jim_Bob

isn't -> Isn't

école -> École

McDonalds -> McDonalds

function toTitleCase(str) {
  return str.replace(/\p{L}+('\p{L}+)?/gu, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.slice(1)
  })
}
风苍溪 2024-07-14 21:55:44

使用 /\S+/g 支持变音符号:

function toTitleCase(str) {
  return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}

console.log(toTitleCase("a city named örebro")); // A City Named Örebro

但是:“sunshine (yellow)”⇒“Sunshine (yellow)”

Use /\S+/g to support diacritics:

function toTitleCase(str) {
  return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}

console.log(toTitleCase("a city named örebro")); // A City Named Örebro

However: "sunshine (yellow)" ⇒ "Sunshine (yellow)"

离旧人 2024-07-14 21:55:44
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
拒绝两难 2024-07-14 21:55:44

试试这个

String.prototype.toProperCase = function(){
    return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, 
        function($1){
            return $1.toUpperCase();
        }
    );
};

例子

var str = 'john smith';
str.toProperCase();

Try this

String.prototype.toProperCase = function(){
    return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, 
        function($1){
            return $1.toUpperCase();
        }
    );
};

Example

var str = 'john smith';
str.toProperCase();
谜兔 2024-07-14 21:55:44

这是我的函数,它负责处理重音字符(对于法语很重要!),并且可以打开/关闭对较低异常的处理。 希望有帮助。

String.prototype.titlecase = function(lang, withLowers = false) {
    var i, string, lowers, uppers;

    string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }).replace(/Mc(.)/g, function(match, next) {
        return 'Mc' + next.toUpperCase();
    });

    if (withLowers) {
        if (lang == 'EN') {
            lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
        }
        else {
            lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
        }
        for (i = 0; i < lowers.length; i++) {
            string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                return txt.toLowerCase();
            });
        }
    }

    uppers = ['Id', 'R&d'];
    for (i = 0; i < uppers.length; i++) {
        string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
    }

    return string;
}

Here is my function that is taking care of accented characters (important for french !) and that can switch on/off the handling of lowers exceptions. Hope that helps.

String.prototype.titlecase = function(lang, withLowers = false) {
    var i, string, lowers, uppers;

    string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }).replace(/Mc(.)/g, function(match, next) {
        return 'Mc' + next.toUpperCase();
    });

    if (withLowers) {
        if (lang == 'EN') {
            lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
        }
        else {
            lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
        }
        for (i = 0; i < lowers.length; i++) {
            string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                return txt.toLowerCase();
            });
        }
    }

    uppers = ['Id', 'R&d'];
    for (i = 0; i < uppers.length; i++) {
        string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
    }

    return string;
}
2024-07-14 21:55:44

我认为最简单的是使用CSS。

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}

I think the simplest is using css.

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}
七月上 2024-07-14 21:55:44

这是使用 css(和 javascript,如果要转换的文本为大写)的另一个解决方案:

html

<span id='text'>JOHN SMITH</span>

js

var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();

css

#text{text-transform:capitalize;}

here's another solution using css (and javascript, if the text you want to transform is in uppercase):

html

<span id='text'>JOHN SMITH</span>

js

var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();

css

#text{text-transform:capitalize;}
む无字情书 2024-07-14 21:55:44

这是一个非常简单的& 简洁的 ES6 函数来执行此操作:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}

export default titleCase;

可以很好地包含在 utilities 文件夹中,并按如下方式使用:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'

Here's a really simple & concise ES6 function to do this:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}

export default titleCase;

Works well included in a utilities folder and used as follows:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'
美人迟暮 2024-07-14 21:55:44

我已经针对土耳其语测试了这个解决方案,它也适用于特殊字符。

function toTitleCase(str) {
  return str.toLocaleLowerCase().replace(
    /(^|Ü|ü|Ş|ş|Ç|ç|İ|ı|Ö|ö|\w)\S*/g,
    (txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),
  )
}

console.log(toTitleCase('İSMAİL HAKKI'))
console.log(toTitleCase('ŞAHMARAN BİNBİR GECE MASALLARI'))
console.log(toTitleCase('TEKNOLOJİ ÜRÜNÜ'))

由于我的数据全部大写,因此我在开头添加了“toLocaleLowerCase”。 如果不需要,您可以将其丢弃。

使用区域设置操作对于非英语语言很重要。

I've tested this solution for Turkish and it works with special characters too.

function toTitleCase(str) {
  return str.toLocaleLowerCase().replace(
    /(^|Ü|ü|Ş|ş|Ç|ç|İ|ı|Ö|ö|\w)\S*/g,
    (txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),
  )
}

console.log(toTitleCase('İSMAİL HAKKI'))
console.log(toTitleCase('ŞAHMARAN BİNBİR GECE MASALLARI'))
console.log(toTitleCase('TEKNOLOJİ ÜRÜNÜ'))

I've added "toLocaleLowerCase" at the begining since I've all caps data. You can discard it if you don't need it.

Using locale operations is important for non-english languages.

杀手六號 2024-07-14 21:55:43

使用:

function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
  );
}

const example = 'john smith';
console.log(`"${example}" becomes "${toTitleCase(example)}"`);

互动示例:

const input = document.querySelector('[name="input"]');
const output = document.querySelector('[name="output"]');

input.addEventListener('change', () => {
  output.value = toTitleCase(input.value);
});

input.addEventListener('keyup', () => {
  output.value = toTitleCase(input.value);
});

output.addEventListener('click', () => output.select());

function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
  );
}
<form>
  Input: <br/>
  <textarea name="input"></textarea>

  <br/>

  Output: <br/>
  <textarea name="output" readonly></textarea>
</form>

Use:

function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
  );
}

const example = 'john smith';
console.log(`"${example}" becomes "${toTitleCase(example)}"`);

Interactive example:

const input = document.querySelector('[name="input"]');
const output = document.querySelector('[name="output"]');

input.addEventListener('change', () => {
  output.value = toTitleCase(input.value);
});

input.addEventListener('keyup', () => {
  output.value = toTitleCase(input.value);
});

output.addEventListener('click', () => output.select());

function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
  );
}
<form>
  Input: <br/>
  <textarea name="input"></textarea>

  <br/>

  Output: <br/>
  <textarea name="output" readonly></textarea>
</form>

风筝有风,海豚有海 2024-07-14 21:55:43

如果 CSS 解决方案满足您的需求,您可以应用 text-transform 控件的 CSS 样式:

text-transform: capitalize;

请注意,这会发生变化:
你好世界你好世界
HELLO WORLDHELLO WORLD(无变化)
emily-jane o'brienEmily-jane O'brien(不正确)
Maria von TrappMaria Von Trapp (不正确)

If a CSS solution meets your needs, you can apply the text-transform CSS style to your controls:

text-transform: capitalize;

Just be aware that this will transform:
hello world to Hello World
HELLO WORLD to HELLO WORLD (no change)
emily-jane o'brien to Emily-jane O'brien (incorrect)
Maria von Trapp to Maria Von Trapp (incorrect)

方圜几里 2024-07-14 21:55:43

一种稍微优雅的方式,改编 Greg Dean 的函数:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

这​​样称呼它:

"pascal".toProperCase();

A slightly more elegant way, adapting Greg Dean's function:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

Call it like:

"pascal".toProperCase();
终弃我 2024-07-14 21:55:43

这是我的版本,在我看来,它很容易理解,也很优雅。

const str = "foo bar baz";
const newStr = str.split(' ')
   .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
   .join(' ');
console.log(newStr);

Here's my version, IMO it's easy to understand and elegant too.

const str = "foo bar baz";
const newStr = str.split(' ')
   .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
   .join(' ');
console.log(newStr);

谁许谁一生繁华 2024-07-14 21:55:43

这是我的函数,它转换为标题大小写,但也将定义的首字母缩写词保留为大写,次要单词保留为小写:

String.prototype.toTitleCase = function() {
  var i, j, str, lowers, uppers;
  str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

例如:

"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"

Here’s my function that converts to title case but also preserves defined acronyms as uppercase and minor words as lowercase:

String.prototype.toTitleCase = function() {
  var i, j, str, lowers, uppers;
  str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

For example:

"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
只怪假的太真实 2024-07-14 21:55:43

您可以立即toLowerCase 字符串,然后toUpperCase 每个单词的第一个字母。 变成非常简单的 1 行:

function titleCase(str) {
  return str.toLowerCase().replace(/\b\w/g, s => s.toUpperCase());
}

console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));

You could immediately toLowerCase the string, and then just toUpperCase the first letter of each word. Becomes a very simple 1 liner:

function titleCase(str) {
  return str.toLowerCase().replace(/\b\w/g, s => s.toUpperCase());
}

console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));

时间你老了 2024-07-14 21:55:43

与其他答案相比,我更喜欢以下答案。 它仅匹配每个单词的第一个字母并将其大写。 代码更简单,更容易阅读,字节数更少。 它保留现有的大写字母以防止首字母缩略词扭曲。 不过,您始终可以先对字符串调用 toLowerCase()

function title(str) {
  return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

您可以将其添加到字符串原型中,这样您就可以'my string'.toTitle(),如下所示:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

示例:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

console.log('all lower case ->','all lower case'.toTitle());
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());

I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call toLowerCase() on your string first.

function title(str) {
  return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

You can add this to your string prototype which will allow you to 'my string'.toTitle() as follows:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

Example:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

console.log('all lower case ->','all lower case'.toTitle());
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());

り繁华旳梦境 2024-07-14 21:55:43

基准

TL;DR

这个基准的获胜者是普通的旧 for 循环:

function titleize(str) {
    let upper = true
    let newStr = ""
    for (let i = 0, l = str.length; i < l; i++) {
        // Note that you can also check for all kinds of spaces  with
        // str[i].match(/\s/)
        if (str[i] == " ") {
            upper = true
            newStr += str[i]
            continue
        }
        newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
        upper = false
    }
    return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.

详细信息

我采用了最流行和最独特的答案,并做出了 与这些的基准

这是我的 MacBook Pro 上的结果:

在此处输入图像描述

为了完整起见,这里是使用的函数:

str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";
function regex(str) {
  return str.replace(
    /\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}

function split(str) {
  return str.
    split(' ').
    map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).
    join(' ');
}

function complete(str) {
  var i, j, str, lowers, uppers;
  str = str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

function firstLetterOnly(str) {
  return str.replace(/\b(\S)/g, function(t) { return t.toUpperCase(); });
}

function forLoop(str) {
  let upper = true;
  let newStr = "";
  for (let i = 0, l = str.length; i < l; i++) {
    if (str[i] == " ") {
      upper = true;
        newStr += " ";
      continue;
    }
    newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();
    upper = false;
  }
  return newStr;
}

请注意,我故意没有更改原型,因为我认为这是一个非常糟糕的做法,我认为我们不应该在我们的回答中提倡这种做法。 仅当您是唯一处理该代码库的人时,这才适用于小型代码库。

如果您想向此基准添加任何其他方法,请评论答案的链接!


编辑 2022 Mac M1: 在我的新电脑上,使用更新的 chrome,分拆获胜。 如果您真的关心特定机器上的性能,您应该自己运行基准测试

Benchmark

TL;DR

The winner of this benchmark is the plain old for loop:

function titleize(str) {
    let upper = true
    let newStr = ""
    for (let i = 0, l = str.length; i < l; i++) {
        // Note that you can also check for all kinds of spaces  with
        // str[i].match(/\s/)
        if (str[i] == " ") {
            upper = true
            newStr += str[i]
            continue
        }
        newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
        upper = false
    }
    return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.

Details

I've taken the most popular and distinct answers and made a benchmark with those.

Here's the result on my MacBook pro:

enter image description here

And for completeness, here are the functions used:

str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";
function regex(str) {
  return str.replace(
    /\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}

function split(str) {
  return str.
    split(' ').
    map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).
    join(' ');
}

function complete(str) {
  var i, j, str, lowers, uppers;
  str = str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

function firstLetterOnly(str) {
  return str.replace(/\b(\S)/g, function(t) { return t.toUpperCase(); });
}

function forLoop(str) {
  let upper = true;
  let newStr = "";
  for (let i = 0, l = str.length; i < l; i++) {
    if (str[i] == " ") {
      upper = true;
        newStr += " ";
      continue;
    }
    newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();
    upper = false;
  }
  return newStr;
}

Note that i deliberately did not change the prototype since I consider it a really bad practice and I don't think we should promote such practice in our answers. This is only ok for small codebases when you're the only one working on it.

If you want to add any other way to do it to this benchmark, please comment a link to the answer !


EDIT 2022 Mac M1: On my new computer, with more recent chrome, split wins. If you really care about performance on a specific machine you should run the benchmark yourself

想你只要分分秒秒 2024-07-14 21:55:43
var result =
  'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())

console.log(result) // This Is Very Interesting

var result =
  'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())

console.log(result) // This Is Very Interesting

沩ん囻菔务 2024-07-14 21:55:43

惊讶地发现没有人提到剩余参数的使用。 这是一个使用 ES6 Rest 参数的简单单行代码。

let str="john smith"
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")
console.log(str)

Surprised to see no one mentioned the use of rest parameter. Here is a simple one liner that uses ES6 Rest parameters.

let str="john smith"
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")
console.log(str)

往事随风而去 2024-07-14 21:55:43

不使用正则表达式仅供参考:

String.prototype.toProperCase = function() {
  var words = this.split(' ');
  var results = [];
  for (var i = 0; i < words.length; i++) {
    var letter = words[i].charAt(0).toUpperCase();
    results.push(letter + words[i].slice(1));
  }
  return results.join(' ');
};

console.log(
  'john smith'.toProperCase()
)

Without using regex just for reference:

String.prototype.toProperCase = function() {
  var words = this.split(' ');
  var results = [];
  for (var i = 0; i < words.length; i++) {
    var letter = words[i].charAt(0).toUpperCase();
    results.push(letter + words[i].slice(1));
  }
  return results.join(' ');
};

console.log(
  'john smith'.toProperCase()
)

贱贱哒 2024-07-14 21:55:43

以防万一您担心这些填充词,您可以随时告诉函数哪些内容不要大写。

/**
 * @param String str The text to be converted to titleCase.
 * @param Array glue the words to leave in lowercase. 
 */
var titleCase = function(str, glue){
    glue = (glue) ? glue : ['of', 'for', 'and'];
    return str.replace(/(\w)(\w*)/g, function(_, i, r){
        var j = i.toUpperCase() + (r != null ? r : "");
        return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
    });
};

希望这可以帮助你。

编辑

如果你想处理前导胶水词,你可以用另一个变量来跟踪这个:

var titleCase = function(str, glue){
    glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
    var first = true;
    return str.replace(/(\w)(\w*)/g, function(_, i, r) {
        var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
        var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
        first = false;
        return result;
    });
};

Just in case you are worried about those filler words, you can always just tell the function what not to capitalize.

/**
 * @param String str The text to be converted to titleCase.
 * @param Array glue the words to leave in lowercase. 
 */
var titleCase = function(str, glue){
    glue = (glue) ? glue : ['of', 'for', 'and'];
    return str.replace(/(\w)(\w*)/g, function(_, i, r){
        var j = i.toUpperCase() + (r != null ? r : "");
        return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
    });
};

Hope this helps you out.

edit

If you want to handle leading glue words, you can keep track of this w/ one more variable:

var titleCase = function(str, glue){
    glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
    var first = true;
    return str.replace(/(\w)(\w*)/g, function(_, i, r) {
        var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
        var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
        first = false;
        return result;
    });
};
以往的大感动 2024-07-14 21:55:43

如果您需要语法正确的答案:

此答案考虑了诸如“of”、“from”等介词。
输出将生成您希望在论文中看到的编辑风格标题。

toTitleCase 函数

考虑语法规则的函数 列于此处
该函数还合并空格并删除特殊字符(根据您的需要修改正则表达式)

const toTitleCase = (str) => {
  const articles = ['a', 'an', 'the'];
  const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
  const prepositions = [
    'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
    'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
  ];

  // The list of spacial characters can be tweaked here
  const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
  const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
  const normalizeStr = (str) => str.toLowerCase().trim();
  const shouldCapitalize = (word, fullWordList, posWithinStr) => {
    if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
      return true;
    }

    return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
  }

  str = replaceCharsWithSpace(str);
  str = normalizeStr(str);

  let words = str.split(' ');
  if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
    words = words.map(w => capitalizeFirstLetter(w));
  }
  else {
    for (let i = 0; i < words.length; i++) {
      words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
    }
  }

  return words.join(' ');
}

确保正确性的单元测试

import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';

describe('toTitleCase', () => {
  it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
    expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
    expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
    expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
  });

  it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
    expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
    expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
    expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
  });

  it('Replace special characters with space', function(){
    expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
    expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
  });

  it('Trim whitespace at beginning and end', function(){
    expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
  });

  it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
    expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
    expect(toTitleCase('the  three Musketeers  And plus ')).to.equal('The Three Musketeers and Plus');
  });
});

请注意,我正在从提供的字符串中删除相当多的特殊字符。 您将需要调整正则表达式来满足项目的要求。

If you need a grammatically correct answer:

This answer takes into account prepositions such as "of", "from", ..
The output will generate an editorial style title you would expect to see in a paper.

toTitleCase Function

The function that takes into account grammar rules listed here.
The function also consolidates whitespace and removes special characters (modify regex for your needs)

const toTitleCase = (str) => {
  const articles = ['a', 'an', 'the'];
  const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
  const prepositions = [
    'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
    'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
  ];

  // The list of spacial characters can be tweaked here
  const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
  const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
  const normalizeStr = (str) => str.toLowerCase().trim();
  const shouldCapitalize = (word, fullWordList, posWithinStr) => {
    if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
      return true;
    }

    return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
  }

  str = replaceCharsWithSpace(str);
  str = normalizeStr(str);

  let words = str.split(' ');
  if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
    words = words.map(w => capitalizeFirstLetter(w));
  }
  else {
    for (let i = 0; i < words.length; i++) {
      words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
    }
  }

  return words.join(' ');
}

Unit Tests to Ensure Correctness

import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';

describe('toTitleCase', () => {
  it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
    expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
    expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
    expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
  });

  it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
    expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
    expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
    expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
  });

  it('Replace special characters with space', function(){
    expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
    expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
  });

  it('Trim whitespace at beginning and end', function(){
    expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
  });

  it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
    expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
    expect(toTitleCase('the  three Musketeers  And plus ')).to.equal('The Three Musketeers and Plus');
  });
});

Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.

七月上 2024-07-14 21:55:43

如果上述解决方案中使用的正则表达式让您感到困惑,请尝试以下代码:

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}

If regex used in the above solutions is getting you confused, try this code:

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}
醉城メ夜风 2024-07-14 21:55:43

我创建了这个函数,它可以处理姓氏(所以它不是标题大小写),例如“McDonald”或“MacDonald”或“O'Toole”或“D'Orazio”。 然而,它不处理带有“van”或“von”的德国或荷兰名字,这些名字通常是小写的......我相信“de”也通常是小写的,例如“Robert de Niro”。 这些问题仍然需要解决。

function toProperCase(s)
{
  return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
          function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}

I made this function which can handle last names (so it's not title case) such as "McDonald" or "MacDonald" or "O'Toole" or "D'Orazio". It doesn't however handle German or Dutch names with "van" or "von" which are often in lower-case... I believe "de" is often lower-case too such as "Robert de Niro". These would still have to be addressed.

function toProperCase(s)
{
  return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
          function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}
三月梨花 2024-07-14 21:55:43

这些答案中的大多数似乎忽略了使用单词边界元字符(\b)的可能性。 Greg Dean 使用它的答案的简短版本:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

也适用于像 Jim-Bob 这样的连字符名字。

Most of these answers seem to ignore the possibility of using the word boundary metacharacter (\b). A shorter version of Greg Dean's answer utilizing it:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

Works for hyphenated names like Jim-Bob too.

滥情空心 2024-07-14 21:55:43

首先,通过 string 转换为数组“noreferrer">用空格分割

var words = str.split(' ');

然后使用 array.map 创建一个包含大写单词的新数组。

var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});

然后用空格加入新数组:

capitalized.join(" ");

function titleCase(str) {
  str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
  var words = str.split(" ");

  var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
  });
  return capitalized.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

注意:

这当然有一个缺点。 这只会将每个单词的第一个字母大写。 对于单词来说,这意味着它将每个由空格分隔的字符串视为 1 个单词。

假设你有:

str = "I'm a little/small tea pot";

这会产生

我是一个小/茶壶

与预期相比,

我是一个小/小茶壶

在这种情况下,使用正则表达式和 .replace 就可以了:

使用 ES6:

const capitalize = str => str.length
  ? str[0].toUpperCase() +
    str.slice(1).toLowerCase()
  : '';

const escape = str => str.replace(/./g, c => `\\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
  let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
  
  return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );

或没有 ES6

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}

function titleCase(str) {
  return str.replace(/[^\ \/\-\_]+/g, capitalize);
}

console.log(titleCase("I'm a little/small tea pot."));

First, convert your string into array by splitting it by spaces:

var words = str.split(' ');

Then use array.map to create a new array containing the capitalized words.

var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});

Then join the new array with spaces:

capitalized.join(" ");

function titleCase(str) {
  str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
  var words = str.split(" ");

  var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
  });
  return capitalized.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

NOTE:

This of course has a drawback. This will only capitalize the first letter of every word. By word, this means that it treats every string separated by spaces as 1 word.

Supposedly you have:

str = "I'm a little/small tea pot";

This will produce

I'm A Little/small Tea Pot

compared to the expected

I'm A Little/Small Tea Pot

In that case, using Regex and .replace will do the trick:

with ES6:

const capitalize = str => str.length
  ? str[0].toUpperCase() +
    str.slice(1).toLowerCase()
  : '';

const escape = str => str.replace(/./g, c => `\\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
  let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
  
  return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );

or without ES6:

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}

function titleCase(str) {
  return str.replace(/[^\ \/\-\_]+/g, capitalize);
}

console.log(titleCase("I'm a little/small tea pot."));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文