[英]how can I get the position of a character in a string?
Im trying to get the position number of a certain character in a string for example I wanna get the number of the 2 in this string我试图获取字符串中某个字符的 position 编号,例如我想获取此字符串中 2 的编号
var = "hello 2 world;"; var = "你好 2 世界;";
Please help me to solve this Im stuck请帮我解决这个我卡住了
var test = 'Hello 2 world';
var pos = test.indexOf('2');
// pos === 6
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value. indexOf() 方法返回调用字符串 object 中第一次出现指定值的索引。 Returns -1 if the value is not found.如果未找到该值,则返回 -1。
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf for more detail有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
let test = "hello 2 world";
let array = test.split('');
for (let i = 0; i < array.length; i++) {
if (!isNaN(array[i])) {
return i;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.