【问题标题】:Match the occurance of a pattern within a string and insert characters in javascript?匹配字符串中模式的出现并在javascript中插入字符?
【发布时间】:2018-05-20 15:23:35
【问题描述】:

例如,假设我们有一个字符串firstName=&lastName=&phoneNumber=&。现在,我们想要匹配模式lastname=,以便我们可以将bobson 插入到& 符号之前的空格中。因此,最终结果将是firstName=&lastName=bobson&phoneNumber=&

【问题讨论】:

  • 堆栈溢出不会很受欢迎。展示你的尝试。

标签: javascript regex string typescript


【解决方案1】:

您可以搜索模式并插入

var string = 'firstName=&lastName=&phoneNumber=&',
    replacement = 'bobson';

console.log(string.replace(/lastName=/, '$&' + replacement));

对于替换,您可以搜索模式并替换模式和&符号之间的所有内容。

var string = 'firstName=&lastName=xx&phoneNumber=&',
    replacement = 'bobson';

console.log(string.replace(/(lastName=)[^&]*/, '$1' + replacement));

【讨论】:

  • 首选!非常感谢!
猜你喜欢
  • 2019-05-27
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2014-05-07
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多