简体   繁体   English

JavaScript正则表达式替换

[英]JavaScript regex replacement

I have this string: 我有这个字符串:

var s = '<span style="font-size:13px">20<div class="lblTitle"></div><span>';    

I'd like to replace the 20 to 40, I tried: 我想将20替换为40,我尝试过:

a.replace(/>(\d*)</, 40)  

But it will result in: 但这将导致:

<span style="font-size:13px"40div class="lblTitle"></div></span>  

the > and < are replaced too... ><也被替换...
What should I do? 我该怎么办?

You could match the > and < and then put them next to the replacement: 您可以将><匹配,然后将它们放在替换项旁边:

.replace(/(>)\d*(<)/, "$140$2")

or simply use: 或简单地使用:

.replace(/>(\d*)</, ">40<")

You are replacing this in string, so you don't need the replacement to be an integer. 您将用字符串替换它,因此不需要替换为整数。

You can't replace a particular group, rather you can use the group value to your replacement value. 您不能替换特定的组,而是可以将组值用作替换值。 You can just use string replacement, regex is not quite required here. 您可以只使用字符串替换,此处并不需要正则表达式。 It would, if you have used the value 20 somewhere in your replacement. 如果您在替换中的某处使用了值20 ,则将使用。

Using regex in this case is a over kill and as well as hamper your performance just to replace a simple text. 在这种情况下使用正则表达式可能会导致过度杀伤,并且会妨碍您的性能,以至于无法替换简单的文本。 Better to use string.replace without regex param. 最好使用不带正则表达式参数的string.replace

a.replace(">20<", 40);

Please mind that, you haven't mentioned that you want to replace all numbers in >/d+< format, and if that is your requirement then just go with regex like this: 请注意,您没有提到要替换>/d+<格式的所有数字 ,如果这是您的要求,则可以使用如下正则表达式:

a.replace(/>(\d*)</, ">40<")

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

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