JavaScript中有办法让String.prototype.replace()返回替换后的值吗?

huangapple go评论63阅读模式
英文:

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;
}

huangapple
  • 本文由 发表于 2023年5月13日 09:32:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76240728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定