English 中文(简体)
JavaScript. 替换在 HTML 标记之外以美元符号包装的内容($)
原标题:JavaScript.Replace content wrapped in dollar signs ($) outside of HTML tags

< 强 > 注意: 我正 - 不试图用正gex 分析 HTML

我试图在字符串中替换任何用美元符号(例如美元)包裹的内容。 我设法找到str.replace (/$([ $]*]$/g), "Hello $1!") , 但我有问题要保证在用 HTML 标记包裹时不会替换这些字符串 。

示例字符串: $ someone$, & lt; a> $welcome$</ a> 和 $another$

表达式: /[gt;]$([ $] *)$[lt;]/g

预期输出 : hello someone!, & lt; a> $welcome</ a>, 并再次向您问好!

实际产出: $ somesonhello, $7.elcomhello, $2. other$

测试代码 : alert ($ someone$,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

fiddle: http://jsfiddle.net/WMWHZ/

谢谢!

最佳回答

请注意, 您的测试案例有 6 美元 。 这里的问题是, 当您尝试检查上一个字符是否不是一个 & gt; 时, 正则表达式会向前移动, 并且匹配 < enger > 4th < / strong > 和 < enger > 5th < / strong > 美元符号, 捕捉 < code>;/ a> 和 " 和制造混乱 " 。

试试这个:

$( div ).text(test.replace(/(^|[^>])$([^<][^$]*)$(?!<)/g, "$1hello $2!"))​

Javascript 不支持常规表达式中的外观, 但是它支持外观头( (?. <) part ) 。 要模仿外观, 您正确地尝试将 [\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

你只需要稍微细化一下, 因为如果美元是在字符串的开头, 这个组没有被捕获。

另外,为了避免上述问题, 您应该检查是否有 & lt; 的 & lt; < em> 在 < / em > 第一美元之后, 所以我在抓取组的起始处加了一个 < code> [lt;] 。 这也意味着它不会在美元符号之间找到空字符串( 如 $ ), 它们必须包含至少一个字符 。

这样,你就会得到预期的结果。

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.