从字符串中抓取第一个字母 [英] Grab first letter from string

查看:145
本文介绍了从字符串中抓取第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

JS

 var a = document.getElementById("quantity");
   var quantity = a.value;

HTML

<select id="quantity" name=''>
  <option title='Option 2' value='2 people'>2 people</option>
  <option title='Option 3' value='3 people'>3 people</option>
  <option title='Option 4' value='4 people'>4 people</option>
  <option title='Option 3' value='5 people'>5 people</option>
  <option title='Option 4' value='6 people'>6 people</option>
</select>

我不能只改变HTML的HTML。如何让它输出第一个字符,所以我实际得到的是一个数字(2,3,4,5或6)。

I can't change the HTML only the JS. How do I get it to output the first char, so what I am actually getting out is a number (either 2,3,4,5 or 6).

I试过这个,但它打破了剧本:

I tried this but it broke the script:

var a = document.getElementById("quantity");
var quantity = a.substring(0,1);


推荐答案

你很接近。你想使用 substring()

You were close. You want to use substring() with value:

var a = document.getElementById("quantity");
a.addEventListener("change", function() {
  var quantity = a.value.substring(0, 1);
  console.log(quantity);
});

<select id="quantity" name=''>
  <option title='Option 2' value='2 people'>2 people</option>
  <option title='Option 3' value='3 people'>3 people</option>
  <option title='Option 4' value='4 people'>4 people</option>
  <option title='Option 3' value='5 people'>5 people</option>
  <option title='Option 4' value='6 people'>6 people</option>
</select>

这篇关于从字符串中抓取第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆