英文:
Is there a way in JavaScript to have String.prototype.replace() return the replaced value?
问题
我正在用JavaScript编写一个简单的词法分析器,我需要一个删除标记值并返回替换后的内容的方法。
我尝试过使用String.prototype.replace()
函数,但它没有起作用。有没有一个简单的方法来执行这个任务?
const eat = (src, regexp) => {
return src.replace(regexp, "");
}
^ 这不起作用,因为String.prototype.replace()
函数仅在替换后返回字符串。
英文:
I am making a simple lexer in JavaScript, and I need a method that deletes the token's value and returns what it has replaced.
I have tried just using the String.prototype.replace()
function, but it hasn't worked. Is there a simple method for performing this task?
const eat = (src, regexp) => {
return src.replace(regexp, "");
}
^ This doesn't work because String.prototype.replace()
simply returns the string after replacement.
答案1
得分: 0
指定一个函数作为替换 可以解决您的问题:
const eat = (src, regexp) => {
let replaced;
src.replace(regexp, (match) =>
{
replaced = match;
return '';
});
return replaced;
}
英文:
Specify a function as replacement can solve your problem:
const eat = (src, regexp) => {
let replaced;
src.replace(regexp, (match) =>
{
replaced = match;
return '';
});
return replaced;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论