从字符和我不想删除的字符中拆分字符串
Split the string from character and that character I don't want remove
我想在 JS 中拆分字符串。我已经知道函数 str.split();
但我想要一些不同的东西。像:
我有字符串 var str = "Hello word"
。我必须将这些字符串从字符 o
中拆分出来,而不是像这样在数组中转换的字符串:array = ['hell', 'o' , ' w', 'o','rd']
var str = "Hello word"
var ary = str.split("o");
// output : ary = ['hell', ' w' ,'rd'];
// I want : ary = ['hell', 'o' , ' w', 'o','rd'];
请任何人帮助我如何获得这样的输出。
你可以试试这个:
var str = "Hello word"
var ary = str.split(/(o)/));
//ary = ['hell', 'o' , ' w', 'o','rd'];
你实际上想要 match
,而不是 split
。
str = "Hello word"
ary = str.match(/o|[^o]+/g)
document.write(ary)
split(/(o)/)
也可以,但请注意:
If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability. (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses)
我想在 JS 中拆分字符串。我已经知道函数 str.split();
但我想要一些不同的东西。像:
我有字符串 var str = "Hello word"
。我必须将这些字符串从字符 o
中拆分出来,而不是像这样在数组中转换的字符串:array = ['hell', 'o' , ' w', 'o','rd']
var str = "Hello word"
var ary = str.split("o");
// output : ary = ['hell', ' w' ,'rd'];
// I want : ary = ['hell', 'o' , ' w', 'o','rd'];
请任何人帮助我如何获得这样的输出。
你可以试试这个:
var str = "Hello word"
var ary = str.split(/(o)/));
//ary = ['hell', 'o' , ' w', 'o','rd'];
你实际上想要 match
,而不是 split
。
str = "Hello word"
ary = str.match(/o|[^o]+/g)
document.write(ary)
split(/(o)/)
也可以,但请注意:
If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability. (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses)