匹配 @(\w+) 并在 javascript 中替换 [英] Match @(\w+) and replace in javascript
问题描述
我正在尝试匹配 div 内容中的 @(\w+) 并将其删除.
这是我尝试过的:http://jsfiddle.net/mxgde6m7/1/.
@(\w+) 有效,但它不会替换为空格.
var content = document.getElementById('contentbox');var find = '@(\w+)';var reg = new RegExp(find, 'g');var 结果 = content.innerHTML.replace(reg, ' ');警报(结果);<div id="contentbox">@d <a href="#" id="5">test </a>
我想要的是:<div id="contentbox"><a href="#" id="5">test </a>
提前致谢.
编辑
好的,一个问题解决了,另一个问题又来了.我的脚本 http://jsfiddle.net/mxgde6m7/9/ 在那里完美运行,但是当我尝试它在我的网站上,只有一半有效.应该用空格替换 @(\w+) 的最后一部分根本不起作用.如果我在控制台(chrome)中复制/粘贴函数的内容,它会起作用,但是如果我粘贴该函数并调用它,则它不起作用.
请帮忙!我被卡住了.
使用 RegExp 构造函数,您需要两个反斜杠 \\
代替每个反斜杠 \
.
var find = '@(\\w+)';
I'm trying to match @(\w+) in a div content and remove it.
Here's what i've tried : http://jsfiddle.net/mxgde6m7/1/ .
@(\w+) works , but it doesn't replace with space.
var content = document.getElementById('contentbox');
var find = '@(\w+)';
var reg = new RegExp(find, 'g');
var result = content.innerHTML.replace(reg, ' ');
alert(result);
<div id="contentbox">@d <a href="#" id="5">test </a>
What i want: <div id="contentbox"><a href="#" id="5">test </a>
</div>
Thanks in advance.
EDIT
Okay, one problem solved, another one came up. My script http://jsfiddle.net/mxgde6m7/9/ works perfectly there, but when i try it on my website, only a half works. The last part where it should replace @(\w+) with space doesn't work at all. If i copy/paste the CONTENT of the function in console(chrome), it works , but if i paste the function and i call it, it doesn't work.
Please help ! I'm stuck.
Using a RegExp constructor, you need two backslashes \\
in place of each backslash \
.
var find = '@(\\w+)';
这篇关于匹配 @(\w+) 并在 javascript 中替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!