如何使用分割?

我需要拆开一个总是这样的字符串:

别的东西。

我需要在另一个输入字段中输入“ something _ else”。目前,这个字符串示例正在动态地添加到一个 HTML 表行,如下所示:

tRow.append($('<td>').text($('[id$=txtEntry2]').val()));

我认为“分离”是解决问题的方法,但我能找到的文档非常少。

312308 次浏览

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ")

If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.

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];

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

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])));

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.

🔸 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