您好我只想在String的第一个单词上运行includes()
方法。我发现有一个可选参数fromIndex
。我宁愿指定toIndex
哪个值是第一个空格的索引,但似乎不存在。
你知道我怎么能做到这一点吗?谢谢!
答案 0 :(得分:0)
你说过你有ngAfterViewInit(): void {
jQuery('.ui-tree-toggler').addClass('d-none');
jQuery('.ui-treenode-content').addClass('shadow');
jQuery('.ui-treenode-content').addClass('fp-tree-node');
this.nodes.forEach(node => {
this.setClasses(node);
});
}
setClasses(node: TreeNode) {
if(!node.children || node.children.length === 0) {
let thisNode = jQuery(`#${node.data.id}`);
let styleParent = thisNode.closest(".ui-treenode")
styleParent[0].classList.add("pl-0");
}
if(!node.data.parentId) {
let thisNode = jQuery(`#${node.data.id}`);
let styleParent = thisNode.closest(".ui-treenode")
styleParent[0].classList.add("pr-0");
}
if (node.children && node.children.length > 0) {
node.children.forEach(child => {
this.setClasses(child);
});
}
}
,所以有两个选择:
改为使用toIndex
:
indexOf
拆分第一个单词(使用var n = str.indexOf(substr);
if (n != -1 && n < toIndex) {
// It's before `toIndex`
}
或split
或其他),然后使用substring
:
includes
(当然,根据您是想要包含还是排他,调整以上if (str.substring(0, toIndex).includes(substr)) {
// It's before `toIndex`
}
的使用。)
答案 1 :(得分:0)
如果它是一个句子,只需将字符串拆分以获得第一个单词
myString = "This is my string";
firstWord = myString.split(" ")[0];
console.log("this doesn't include what I'm looking for".includes(firstWord));
console.log("This does".includes(firstWord));
&#13;
答案 2 :(得分:0)
您可以尝试以下方法并创建新方法
let str = "abc abdf abcd";
String.prototype.includes2 = function(pattern,from =0,to = 0) {
to = this.indexOf(' ');
to = to >0?to: this.length();
return this.substring(from, to).includes(pattern);
}
console.log(str.includes2("abc",0,3));
console.log(str.includes2("abc",4,8));
console.log(str.includes2("abc"));
console.log(str.includes2("abd"))
&#13;
答案 3 :(得分:0)
您可以拆分字符串并传递给索引为0的include方法
var a = "this is first word of a String";
console.log(a.includes(a.split(' ')[0]));
&#13;