我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
在JavaScript中,你可以这样做:
Const x = 'some string'; console.log (x。substring (0,1));
其他回答
在JQuery中你可以使用: 在类中选择选项:
$('.className').each(function(){
className.push($("option:selected",this).val().substr(1));
});
值:
$('.className').each(function(){
className.push($(this).val().substr(1));
});
在ID为文本值:
$("#id").val().substr(1)
var x = "somestring"
alert(x.charAt(0));
charAt()方法允许您指定所需字符的位置。
你要做的是获取数组x的位置上的字符,它没有定义为x不是数组。
已经12年了,只有一个开发人员提到了regexp,但它是一种更简单的方法:
const str = 'string';
str.match(/\w/); // >> s
它将返回给定字符串中的第一个字符类单词。
你可以用任何一个。
所有这些都有一点不同 所以在条件语句中使用时要小心。
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 console.log(string.at(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 console.log(string.at(0)); //o/p:- undefined
看起来我迟到了,但试试下面的解决方案,我个人认为最好的解决方案:
var x = "testing sub string"
alert(x[0]);
alert(x[1]);
输出应该显示警报与以下值: “t” “e”