使用搜索和切片

时间:2014-03-19 21:13:13

标签: 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 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

第二次执行单应返回是,而txt应该只剩下冬天了。

2 个答案:

答案 0 :(得分:0)

这是因为搜索方法返回匹配的第一个索引。鉴于您正在寻找单个空格字符,它在每个字符串后面返回的索引是0,因为字符串现在以空格开头。

我建议在返回之前更改行:

this.txt = this.txt.slice(n).trim(); //txt now becomes everything after the word

答案 1 :(得分:0)

写作时

var n = this.txt.search(/\s/); //locate the first word

\s是一个空格字符,我认为你的正则表达式无法搜索一个单词。

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

enter image description here

/\S+/.exec('winter is coming'); // returns 'winter'
/\S+/.exec(' is coming');       // returns 'is'
/\S+/.exec('  coming');         // returns 'coming'