在JavaScript中人性化字符串

Chr*_*ini 8 javascript string humanize

我如何将字符串人性化?基于以下标准:

  • 删除前导下划线(如果有).
  • 如果有的话,用空格替换下划线.
  • 资本化第一个词.

例如:

this is a test -> This is a test
foo Bar Baz    -> Foo bar baz
foo_bar        -> Foo bar
foo_bar_baz    -> Foo bar baz
foo-bar        -> Foo-bar
fooBarBaz      -> FooBarBaz
Run Code Online (Sandbox Code Playgroud)

fun*_*urm 8

最好是使用一些正则表达式:

^[\s_]+|[\s_]+$在字符串的最开头(^)或最后($)处捕获1个或多个空格字符或下划线.请注意,这也会捕获换行符.用空字符串替换它们.

[_\s]+ 再次捕获一个或多个空格字符或下划线,因为字符串开头/结尾处的字符串已消失,请替换为1个空格.

^[a-z]在字符串的开头抓一个小写字母.替换为匹配的大写版本(您需要一个回调函数).

联合:

function humanize(str) {
  return str
      .replace(/^[\s_]+|[\s_]+$/g, '')
      .replace(/[_\s]+/g, ' ')
      .replace(/^[a-z]/, function(m) { return m.toUpperCase(); });
}

document.getElementById('out').value = [
  '    this is a test',
  'foo Bar Baz',
  'foo_bar',
  'foo-bar',
  'fooBarBaz',
  '_fooBarBaz____',
  '_alpha',
  'hello_ _world,   how    are________you?  '
].map(humanize).join('\n');
Run Code Online (Sandbox Code Playgroud)
textarea { width:100%; }
Run Code Online (Sandbox Code Playgroud)
<textarea id="out" rows="10"></textarea>
Run Code Online (Sandbox Code Playgroud)


elc*_*nrs 5

这涵盖了所有情况:

var tests = [
  'this is a test',
  'foo Bar Baz',
  ...
]

var res = tests.map(function(test) {
  return test
    .replace(/_/g, ' ')
    .trim()
    .replace(/\b[A-Z][a-z]+\b/g, function(word) {
      return word.toLowerCase()
    })
    .replace(/^[a-z]/g, function(first) {
      return first.toUpperCase()
    })
})

console.log(res)
/*
[ 'This is a test',
  'Foo bar baz',
  'Foo bar',
  'Foo-bar',
  'FooBarBaz' ]
*/
Run Code Online (Sandbox Code Playgroud)