简体   繁体   English

在JavaScript中将字符串拆分为2个变量

[英]Split a String into 2 Variables in javascript

I am wanting to convert a string into 2 variables.. 我想将字符串转换为2个变量。

I have created a variable and I am using substring to split it, however I can't seem to get it working. 我已经创建了一个变量,并且正在使用子字符串来拆分它,但是我似乎无法使其正常工作。

If I create a alert message it display's the orignal variable that I want split up (so I know there is something there) 如果创建警报消息,它将显示我想要分割的原始变量(因此我知道那里有东西)

My code looks like this: 我的代码如下所示:

// variable 'ca' is set from a XML Element Response
alert(ca); // displays a string (eg. 123456789) - which does display fine
alert(ca.substring(0,1));  // should alert 1 but it stops and nothing is displayed

but I add ca = "123456789"; 但我添加ca =“ 123456789”; as below, it works.. 如下所示。

ca = "123456789";
alert(ca); // displays a string (eg. 123456789) - which does display fine
alert(ca.substring(0,1));  // should alert 1 but it stops and nothing is displayed

however the variable ca has something set and is display right before the substring is used.. 但是,变量ca已设置,并在使用子字符串之前显示。

anyone know what I might be doing wrong? 有人知道我可能做错了吗?

Your variable doesn't contain a string, it contains something else, probably a number. 您的变量不包含字符串,而是包含其他内容,可能是数字。

Convert the value to a string, to be able to use string methods on it: 将值转换为字符串,以便能够在其上使用字符串方法:

ca = ca.toString();

My guess is that ca doesn't contain a string but a number. 我的猜测是ca不包含字符串,而是一个数字。 Does it work when you cast the variable to a string? 当您将变量转换为字符串时,它起作用吗?

alert(String(ca).substring(0,1));

(Note that you can check what a variable contains with the typeof operator: (请注意,您可以使用typeof运算符检查变量包含的内容:

console.log(typeof ca);
// number
console.log(typeof String(ca));
// string

UPDATE: both ca.toString() and String(ca) should work, but I personally prefer String(ca) since that will also work if ca is null or undefined . 更新: ca.toString()String(ca)都应该工作,但是我个人更喜欢String(ca)因为如果ca为nullundefined ,那也可以工作。

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

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