简体   繁体   English

跳过字符串的一部分并用正则表达式替换匹配

[英]skip part of a string and replace match with regular expression

I need to replace part of a string but the code I have replaces the whole string and I want to only relace the text after the = equals sign based on the key name.我需要替换字符串的一部分,但我的代码替换了整个字符串,我只想根据键名替换 = 等号之后的文本。 I need the regular expression to skip the key word value= and then replace the value that it equals.我需要正则表达式来跳过关键字 value= 然后替换它等于的值。 I have part of it working in the regular expression but it does a full match.我有一部分在正则表达式中工作,但它完全匹配。

    /(?:value\=)([A-Za-z{}": ',&-=\\]+)$/

name = test
key = value
value = {
  "first": 'John',
  'Last': 'Doe'
}
value = first = John & last = Doe

tester测试员

 var data = "value=first_name=John&last_name=Doe;" .replace(/^(?:value\\=)([A-Za-z{}": ',&-=\\\\]+)$/g, 'first_name=Homer&last_name=Simspon'); console.log(data); /* data = value=first_name=John&last_name=Doe which should be value=first_name=Homer&last_name=Simspon */

You can use capturing groups, $1, $2, etc. I've used the wildcard .* regex below, but you could probably make it more specific to the key-val pairs you expect to see.您可以使用捕获组、$1、$2 等。我在下面使用了通配符 .* 正则表达式,但您可能可以使其更具体到您希望看到的键值对。

 var data = "value=first_name=John&last_name=Doe;" .replace(/(value\\=).*(;)/g, '$1first_name=Homer&last_name=Simspon$2'); console.log(data); /* data = value=first_name=John&last_name=Doe which should be value=first_name=Homer&last_name=Simspon */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM