简体   繁体   English

将变量插入正则表达式(JavaScript)不起作用

[英]Inserting variable into regex (JavaScript) isn't working

This is my code: 这是我的代码:

var newLT = 'locTable'+(l+locations);
var findLT = 'locTable'+l;
var regex = new RegExp("/\b" + findLT + "\b/g");
locOrig = locOrig.replace(regex, newLT);

I'm trying to replace all instances of 'locTable(#number here)' with the newLT variable. 我正在尝试用newLT变量替换'locTable(#number here)'的所有实例。

So for example if this was in a string <input id="locTable3_0"> ideally I could replace just the 'locTable3' part which is stored in findLT with the value in newLT. 因此,例如,如果在字符串<input id="locTable3_0"> ,则可以将newLT中的值仅替换存储在findLT中的'locTable3'部分。

Any tips on what I'm doing wrong? 关于我在做什么的任何提示?

EDIT: For clarity: 编辑:为清楚起见:

Say I have the string <input id="locTable3_0"> . 说我有字符串<input id="locTable3_0">

variable newLT is equal to locTable4 变量newLT等于locTable4

variable findLT is equal to locTable3 变量findLT等于locTable3

I want to have a regex which finds locTable3 and replaces it with locTable4 so that my resulting string is <input id="locTable4_0"> 我想有一个找到locTable3并将其替换为locTable4的正则表达式,以便我得到的字符串为<input id="locTable4_0">

Updated: I think I god it now 更新:我想我现在知道了

var regex = /locTable\d/;
var newString = 'something_else_3'
var string = "locTable3_0";
var result = string.replace(regex1, newString);

this will result in something_else_3_0 这将导致something_else_3_0

  • /.../xyz is short notation, that won't work here /.../xyz是简写,在这里不起作用

new RegExp("/\\b" + findLT + "\\b/g"); => new RegExp("\\b" + findLT + "\\b", "g"); => new RegExp("\\b" + findLT + "\\b", "g");

  • You are passing string to RegExp constructor, so you have to escape special chars twice: 您要将字符串传递给RegExp构造函数,因此必须两次转义特殊字符:

new RegExp("\\b" + findLT + "\\b", "g"); => new RegExp("\\\\b" + findLT + "\\\\b", "g"); => new RegExp("\\\\b" + findLT + "\\\\b", "g");

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

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