简体   繁体   English

如何获取字符串的第一个字符?

[英]How to get first character of string?

I have a string, and I need to get its first character.我有一个字符串,我需要获取它的第一个字符。

 var x = 'somestring'; alert(x[0]); //in ie7 returns undefined

How can I fix my code?我该如何修复我的代码?

What you want is charAt .你想要的是charAt

var x = 'some string';
alert(x.charAt(0)); // alerts 's'

In JavaScript you can do this:在 JavaScript 中,您可以这样做:

 const x = 'some string'; console.log(x.substring(0, 1));

You can use any of these.您可以使用其中任何一种。

There is a little difference between all of these So be careful while using it in conditional statement.所有这些之间都有一点不同所以在条件语句中使用它时要小心。

var string = "hello world";
console.log(string.slice(0,1));     //o/p:- h
console.log(string.charAt(0));      //o/p:- h
console.log(string.substring(0,1)); //o/p:- h
console.log(string.substr(0,1));    //o/p:- h
console.log(string[0]);             //o/p:- h


var string = "";
console.log(string.slice(0,1));     //o/p:- (an empty string)
console.log(string.charAt(0));      //o/p:- (an empty string)
console.log(string.substring(0,1)); //o/p:- (an empty string)
console.log(string.substr(0,1));    //o/p:- (an empty string)
console.log(string[0]);             //o/p:- undefined

 const x = 'some string'; console.log(x.substring(0, 1));

Example of all method所有方法的示例

First : string.charAt(index)第一string.charAt(index)

Return the caract at the index index返回索引index处的caract

 var str = "Stack overflow"; console.log(str.charAt(0));

Second : string.substring(start,length);第二个string.substring(start,length);

Return the substring in the string who start at the index start and stop after the length length返回字符串中从索引start到长度length之后停止的子字符串

Here you only want the first caract so : start = 0 and length = 1在这里,您只需要第一个字符: start = 0length = 1

 var str = "Stack overflow"; console.log(str.substring(0,1));

Alternative : string[index]替代方案string[index]

A string is an array of caract.字符串是一个字符数组。 So you can get the first caract like the first cell of an array.所以你可以像数组的第一个单元格一样获得第一个字符。

Return the caract at the index index of the string返回字符串index处的字符

 var str = "Stack overflow"; console.log(str[0]);

var x = "somestring"
alert(x.charAt(0));

The charAt() method allows you to specify the position of the character you want. charAt() 方法允许您指定所需字符的位置。

What you were trying to do is get the character at the position of an array "x", which is not defined as X is not an array.您试图做的是在数组“x”的位置获取字符,该字符未定义为 X 不是数组。

您甚至可以使用slice截断所有其他字符:

x.slice(0, 1);
var str="stack overflow";

firstChar  = str.charAt(0);

secondChar = str.charAt(1);

Tested in IE6+ , FF , Chrome , safari .IE6+FFChromesafari 中测试

也试试这个:

x.substr(0, 1);

Looks like I am late to the party, but try the below solution which I personally found the best solution:看起来我参加聚会迟到了,但请尝试以下我个人找到的最佳解决方案:

var x = "testing sub string"
alert(x[0]);
alert(x[1]);

Output should show alert with below values: "t" "e"输出应显示带有以下值的警报:“t”“e”

x.substring(0,1)

Details细节

substring(start, end) extracts the characters from a string, between the 2 indices "start" and "end", not including "end" itself. substring(start, end)从字符串中提取字符,在 2 个索引“start”和“end”之间,包括“end”本身。

Special notes特别说明

  • If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1, 4) == str.substring(4, 1).如果“start”大于“end”,则此方法将交换两个参数,即 str.substring(1, 4) == str.substring(4, 1)。
  • If either "start" or "end" is less than 0, it is treated as if it were 0.如果“开始”或“结束”小于 0,则将其视为 0。

in Nodejs you can use Buffer :在 Nodejs 中,您可以使用 Buffer :

let str = "hello world"
let buffer = Buffer.alloc(2, str) // replace 2 by 1 for the first char
console.log(buffer.toString('utf-8')) // display he
console.log(buffer.toString('utf-8').length) // display 2

你可以这样使用:

'Hello Mr Been'.split(' ').map( item => item.toUpperCase().substring(0, 1)).join(' ');

charAt() do not work if it has a parent prop charAt()有父属性,则它不起作用
ex parent.child.chartAt(0)parent.child.chartAt(0)
use parent.child.slice(0, 1)使用parent.child.slice(0, 1)

You can use any of the following:您可以使用以下任何一项:

let userEmail = "email";
console.log(userEmail[0]); // e
console.log(userEmail.charAt(0)); // e
console.log(userEmail.slice(0, 1)); // e
console.log(userEmail.substring(0, 1)); // e
console.log(userEmail.substr(0, 1)); // e
console.log(userEmail.split("", 1).toString()); // e
console.log(userEmail.match(/./)[0]); // e

Simple Method would be 简单的方法是

const z ="sdsdsd"

console.log(z[0])    // 's'

and use pollyfills 并使用polyfills

It's been 10 years yet no answer mentioned RegExp .已经 10 年了,但没有人提到RegExp

 var x = 'somestring'; console.log(x.match(/./)[0]);

You can use as well:您也可以使用:

var x = "somestring";

console.log(x.split("")[0]); // output "s"

This should work with older browsers.这应该适用于较旧的浏览器。

Since every string is an array, probably the most succinct solution is by using the new spread operator:由于每个字符串都是一个数组,最简洁的解决方案可能是使用新的展开运算符:

const x = 'somestring'
const [head, ...tail] = x
console.log(head) // 's'

bonus is you can now access the total string but the first character using join('') on tail :好处是您现在可以访问整个字符串,但第一个字符在tail使用join('')

console.log(tail.join('')) // 'omestring'

For any string str = "Hello World"对于任何字符串 str = "Hello World"

str.split(' ').map( item => item.toUpperCase().substring(0, 1)).join(' '); str.split(' ').map( item => item.toUpperCase().substring(0, 1)).join(' ');

Output: HW Output:硬件

There are many ways to find the string first character in Javascript. I think the easiest way to find is the string.charAt() method.查找Javascript中的字符串第一个字符的方法有很多种,我认为最简单的查找方法是string.charAt()方法。 This method takes an index number as a parameter and returns the index value.此方法将索引号作为参数并返回索引值。 If you didn't give any parameter by default its returns the first character of the string.如果你没有给出任何参数,默认情况下它返回字符串的第一个字符。

 const str = "Bangladesh"; const firstCharacter = str.charAt(0); const secondCharacter = str.charAt(1); console.log(firstCharacter) console.log(secondCharacter)

It's been 12 years and just one dev mentioned regexp, but it's a simpler way:已经 12 年了,只有一个开发人员提到了正则表达式,但这是一种更简单的方法:

const str = 'string';

str.match(/\w/); // >> s

It will return the first character-class-word from the given string.它将返回给定字符串中的第一个字符类单词。

in JQuery you can use: in class for Select Option:在 JQuery 中,您可以使用:在 Select Option 类中:

$('.className').each(function(){
    className.push($("option:selected",this).val().substr(1));
});

in class for text Value:在类文本值:

$('.className').each(function(){
    className.push($(this).val().substr(1));
});

in ID for text Value:在文本值的 ID 中:

$("#id").val().substr(1)
var string  = "Hello World";
console.log(charAt(0));

The charAt(0) is JavaScript method, It will return value based on index, here 0 is the index for first letter. charAt(0) 是 JavaScript 方法,它会根据索引返回值,这里 0 是第一个字母的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM