简体   繁体   English

用javascript中的正则表达式替换字符串中的字符

[英]Replace in-string characters with regex in javascript

i'm pretty unconfident with regex and i need to do this simple work: i have an input string like this: 我对正则表达式非常不确定,我需要做以下简单的工作:我有一个像这样的输入字符串:

<a id="randomid">some text ( +1 even more text)</a>

now i need to replace that "1", i know it will always be between ( + and a space, how can i do this with regex? 现在我需要替换为“ 1”,我知道它将一直在( +和空格之间,我如何使用正则表达式来做到这一点?

That string is generated by ASP.NET inside a asp:HyperLink component, my first try was to generate that number inside a <span> with know id, but looks like asp.net remove all my html tags inside a ASP component 该字符串是由ASP.NET在asp:HyperLink组件内部生成的,我的第一次尝试是在具有已知ID的<span>内部生成该数字,但是看起来asp.net删除了我在ASP组件内部的所有html标记

If your assumption is correct, this will also work for you, it will replace the first occurance of "( +number" with "( +replaceNumber". 如果您的假设是正确的,那么这对您也将起作用,它将用“(+ replaceNumber”代替“(+ number)的第一次出现。

var regex = /\(\s+\+[0-9]+/
var replaceNumber = 2;
$('a#randomid').text().replace(regex, "( +"+replaceNumber);

TO replace all the occurances change the regex to 要替换所有情况,请将正则表达式更改为

var regex = /\(\s+\+[0-9]+/g

Assuming you're using jQuery... 假设您使用的是jQuery ...

$('a#randomid').text().replace(/(.+ \( \+)([0-9]+)(.+)/, "$12$3")

Will give you... 会给你...

some text ( +2 even more text)

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

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