简体   繁体   English

如何替换ap标签内的所有“/”

[英]How to replace all “/” within a p tag

I would like to replace all forward slashes within ap tag but I cannot see what I am doing wrong. 我想替换ap标签内的所有正斜杠,但我看不出我做错了什么。

 $(document).ready(function() { var content = $("p").text(); content.replace(/\\//g, 'ForwardSlash'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>YOYOYO / yoyoyoy / YIYYIYIYI ddwqd w/ dwdwdw/ dwd / dwd /</p> <div>YOYOYO / yoyoyoy / YIYYIYIYI ddwqd w/ dwdwdw/ dwd / dwd /</div> 

The reason that I want to do this is because a site I am making requires all the forward slashes to be a different colour to the text within the tag and as I am building the site within a CMS I am trying to make it easy to edit. 我想这样做的原因是因为我正在制作的网站要求所有正斜杠与标签内的文本颜色不同,因为我在CMS中构建网站我试图让它易于编辑。 The crude way of doing this would be to make the client paste spans with class names or inline styles. 这样做的粗略方法是使客户端粘贴跨越类名或内联样式。 Hopefully I can do one of those things for him automatically using your help and the code above. 希望我可以使用您的帮助和上面的代码自动为他做其中一件事。

You were on the right track. 你走在正确的轨道上。 But, know that replace() does not take a string with a reference and modify it. 但是,要知道replace()不接受带引用的字符串并修改它。 Rather, it returns a result and you will have to use that result 相反,它返回一个结果,你将不得不使用该结果

 $(document).ready(function() { $('p').each(function() { var content = $(this).text(); content = content.replace(/\\//g, 'ForwardSlash'); $(this).text(content); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>YOYOYO / yoyoyoy / YIYYIYIYI ddwqd w/ dwdwdw/ dwd / dwd /</p> <p>YOYOYO / yoyoyoy / YIYYIYIYI ddwqd w/ dwdwdw/ dwd / dwd /</p> 

You forgot to apply the result back to the p (and to the content variable, as content itself does not get modified, it returns the modified string , so you would have to reassign the result to content if you want to do it in multiple steps). 您忘记将结果应用回p (和content变量,因为content本身不会被修改,它会返回 修改后的字符串 ,因此如果您想在多个步骤中执行此操作,则必须将结果重新分配给content )。

Also, as @dman2306 mentioned, it might be better to use html() instead of text() as any other nodes are stripped when using text, including <em> and <strong> tags, which are often used inside <p> tags. 另外,正如@ dman2306所提到的,使用html()而不是text()可能会更好,因为在使用文本时会删除任何其他节点,包括<em><strong>标记,这些标记通常在<p>标记内使用。 Although this would require a regex pattern to not remove any slashes that were preceded by a < ... 虽然这需要一个正则表达式模式, 不要删除前面带有< ...的任何斜线。

 $(document).ready(function() { var content = $("p").text().replace(/\\//g, 'ForwardSlash'); $("p").text(content); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>YOYOYO / yoyoyoy / YIYYIYIYI ddwqd w/ dwdwdw/ dwd / dwd /</p> <div>YOYOYO / yoyoyoy / YIYYIYIYI ddwqd w/ dwdwdw/ dwd / dwd /</div> 

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

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