【发布时间】:2013-03-22 04:29:10
【问题描述】:
我对这个递归函数感到很困惑。我用它来突出显示文本框中的单词,但它给了我一些奇怪的输出:
should be:
#define
testing #define
but instead it's:
testing #define
testing #define
这是代码
function replace_all( text, old_str, new_str ){
index_of = text.indexOf( old_str );
if( index_of != -1 ){
old_text = text.substring( 0, index_of );
new_text = text.substring( index_of + old_str.length );
new_text = replace_all( new_text, old_str, new_str );
text = old_text + new_str + new_text;
}
return text;
}
关于函数有什么问题的任何想法?它似乎正在用找到的最后一个关键字替换所有旧关键字。
【问题讨论】:
-
function replace_all(text,ostr,nstr) {return text.replace(new RegExp(ostr,"g"),nstr);}有什么问题? -
你是怎么调用
replace_all函数的? -
@Kolink 成功了。我从来没有查找过正则表达式,但它似乎可以完成这项工作。
标签: javascript string parsing recursion