Javascript 使用搜索和切片

Javascript 使用搜索和切片,javascript,Javascript,我有一个定义如下的类: function Take(){ Take.prototype.txt = "winter is coming" } Take有一个函数,可以从txt属性中删除并返回一个单词 Take.prototype.single = function(){ var n = this.txt.search(/\s/); //locate the first word var word = this.txt.slice(0, n); //slice that

我有一个定义如下的类:

function Take(){
    Take.prototype.txt = "winter is coming"
}
Take有一个函数,可以从txt属性中删除并返回一个单词

Take.prototype.single = function(){
    var n = this.txt.search(/\s/); //locate the first word
    var word = this.txt.slice(0, n); //slice that word out 
    this.txt = this.txt.slice(n); //txt now becomes everything after the word
    return word;
} 
当我执行single()一次时,我得到:

winter 
txt中剩下的是

_is coming //underscore to display a space there
但是如果我再次执行代码,我什么也得不到,txt仍然有

_is coming //underscore to display a space there

single的第二次执行应该返回,txt应该只剩下winter。

这是因为搜索方法返回匹配的第一个索引。假设您正在查找单个空格字符,那么它在第一个空格字符之后每次返回的索引都是
0
,因为字符串现在以空格开头

我建议在返回之前将线路更改为以下内容:

this.txt=this.txt.slice(n.trim()//现在,当您编写时,txt将成为单词

之后的所有内容

var n = this.txt.search(/\s/); //locate the first word
\s
是一个空格字符,我认为您的正则表达式无法搜索单词

请改为尝试
\S+
\S
=不是空格字符)


尝试键入
'is coming'。在控制台中搜索(/\s/)
,我敢打赌当字符串以空格开头时,你会得到零。然后你会得到
这个.txt.slice(0,0)
,它不会给你任何东西。根据你的建议,下面的输出是winter即将到来。由于某种原因,g队被挡在了后面。
/\S+/.exec('winter is coming'); // returns 'winter'
/\S+/.exec(' is coming');       // returns 'is'
/\S+/.exec('  coming');         // returns 'coming'