获取JavaScript中字符串的所有子字符串 [英] Get all substrings of a string in JavaScript
本文介绍了获取JavaScript中字符串的所有子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下功能,可从JavaScript中的字符串获取所有子字符串.我知道这是不正确的,但我觉得我正在以正确的方式进行操作.任何建议都很好.
I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
很抱歉,如果我的问题不清楚.子字符串是指字符串中字母的所有组合(不一定是实际的单词),因此,如果字符串为"abc",则可以使用[a,ab,abc,b,ba,bac等...]谢谢对于所有的回应.
Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
推荐答案
子字符串需要两个嵌套循环.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于获取JavaScript中字符串的所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文