简体   繁体   English

如何在javascript中匹配部分之后替换子字符串?

[英]How to replace sub string after the portion of match in javascript?

I'd like to change everything after '=img' into something else, following code does not work: 我想将'= img'之后的所有内容更改为其他内容,以下代码不起作用:

var j = '/test/123=img?xyze'
j.replace(/=img\.*/, '');

Any idea how? 任何想法如何? Thanks, 谢谢,

AC 交流电

var j = '/test/123=img?xyze'
j=j.replace(/(=img)(.*)/, '$1_somethingElse');
console.log(j); //  "/test/123=img_somethingElse"

$1 is =img and the rest would be in $2 if you needed it. $1=img ,如果需要,其余的将在$2

Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Switching_words_in_a_string 进一步阅读: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Switching_words_in_a_string

Change to this: 更改为此:

var j = '/test/123=img?xyze';
var replacementText = 'something-else';
j = j.match(/^.+?=img/i)[0] + replacementText;

Otherwise, this little snippet below will give you all the parts of the query surrounding what you want to change, if you so desire: 否则,如果您愿意,下面的小片段将为您提供围绕您要更改的内容的查询的所有部分:

var j = '/test/123=img?xyze';
var replacementText = 'something-else';
var parts = j.match(/^(.+?)(=img)(.+)$/i);

// /test/123=img?xyze : parts[0]
// /test/123          : parts[1]
// =img               : parts[2]
// ?xyze              : parts[3]

You would then do this for replacing: 然后,您将执行以下操作来替换:

j = parts[1] + parts[2] + replacementText;

 var j = '/test/123=img?xyze' var x = j.substr(0, j.indexOf('=img')) + '=img' console.log(x) 

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

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