Javascript 如何使用拆分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2555794/
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
How to use split?
提问by Matt
I need to break apart a string that always looks like this:
我需要拆开一个看起来像这样的字符串:
something -- something_else.
某物——something_else。
I need to put "something_else" in another input field. Currently, this string example is being added to an HTML table row on the fly like this:
我需要将“something_else”放在另一个输入字段中。目前,这个字符串示例正在被动态添加到 HTML 表格行中,如下所示:
tRow.append($('<td>').text($('[id$=txtEntry2]').val()));
I figure "split" is the way to go, but there is very little documentation that I can find.
我认为“拆分”是要走的路,但我能找到的文档很少。
回答by Felix Kling
Documentation can be found e.g. at MDN. Note that .split()is nota jQuery method, but a native string method.
文档可以在例如MDN找到。请注意,.split()是不是一个jQuery方法,但本地字符串的方法。
If you use .split()on a string, then you get an array back with the substrings:
如果你.split()在一个字符串上使用,那么你会得到一个带有子字符串的数组:
var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"
If this value is in some field you could also do:
如果此值在某个字段中,您还可以执行以下操作:
tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));
回答by Charles Boyung
If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.
如果是基本的 JavaScript split 函数,看文档,JavaScript split() 方法。
Basically, you just do this:
基本上,您只需执行以下操作:
var array = myString.split(' -- ')
Then your two values are stored in the array - you can get the values like this:
然后你的两个值存储在数组中 - 你可以得到这样的值:
var firstValue = array[0];
var secondValue = array[1];
回答by vittore
Look in JavaScript split() Method
查看 JavaScript split() 方法
Usage:
用法:
"something -- something_else".split(" -- ")
回答by Hasan Sefa Ozalp
According to MDN, the
split()method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.
根据MDN,该
split()方法将一个 String 划分为一组有序的子字符串,将这些子字符串放入一个数组中,然后返回该数组。
Example
例子
var str = 'Hello my friend'
var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]
In your case
在你的情况下
var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]
console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

