使用特殊字符拆分变量 - Javascript - jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6410459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split variable using a special character - Javascript - jQuery
提问by blasteralfred Ψ
I have a variable var i = "my*text"
I want to split it using special character *
. I mean, I want to generate var one
= "my" and var two
= "text" from the above variable.
我有一个变量,var i = "my*text"
我想使用特殊字符将其拆分*
。我的意思是,我想从上面的变量中生成var one
= "my" 和var two
= "text"。
How can I do this using jQuery and (or) Javascript??
我如何使用 jQuery 和(或)Javascript 来做到这一点?
Thanks in advance...
提前致谢...
回答by Shakti Singh
values=i.split('*');
one=values[0];
two=values[1];
回答by Pranay Rana
use string.split(separator, limit)
用 string.split(separator, limit)
<script type="text/javascript">
var str="my*text";
str.split("*");
</script>
回答by karim79
Just to add, the comma operator is your friend here:
补充一点,逗号运算符是您的朋友:
var i = "my*text".split("*"), j = i[0], k = i[1];
alert(j + ' ' + k);
回答by Guffa
You can use the split
method:
您可以使用以下split
方法:
var result = i.split('*');
The variable result now contains an array with two items:
变量 result 现在包含一个包含两个项目的数组:
result[0] : 'my'
result[1] : 'text'
You can also use string operations to locate the special character and get the strings before and after that:
您还可以使用字符串操作来定位特殊字符并获取其前后的字符串:
var index = i.indexOf('*');
var one = i.substr(0, index);
var two = i.substr(index + 1, i.length - index - 1);