如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

使用:

<input type="text" onKeyup="ucfirst(this)" />

其他回答

尝试下列功能:

function capitalize (string) {
  return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}

使用:

capitalize('hello, world!')

结果:

Hello, world!

带有箭功能

let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"

用火箭功能,另一种解决方案

let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"

与 Array 和 地图()

let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]

我需要做一个完整的名字资本化,如阿米尔·迪亚菲(Amir Diafi),所以我分裂了链条,以获得这些名字的序列,并资本化了每个字母的第一字母。

const value = 'amir diafi karim mohammed' const splited_names = value.split(' ') let capitalizedValue = '' for (const iterator of splited_names) { capitalizedValue += ` ${iterator.charAt(0).toUpperCase()}${iterator.slice(1)}` } capitalizedValue.trim() console.log(capitalizedValue) //amir diafi karim => Amir Diafi Karim

好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。

因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。

首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉

这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;