使用其他javascript删除字符串中字符的所有实例 [英] remove all instances of a character in a string with something else javascript
问题描述
我需要用空格替换所有<br />
.以下是动态吐出的字符串,我需要隐藏br标签...
I need to replace all <br />
with a space. The below is the string that gets spitted out dynamically and i need to hide the br tags...
M,W,Th,F 7:30 AM - 4:00 PM<br />Tu 7:30 AM - 6:00 PM<br />
我在做什么错吗?是否可以用逗号替换所有其他br标签,但最后一个将用空格代替
What am i doing wrong?is it possible to replace all other br tags with a comma except the last one, which will be repalced by a space
$('.WorkingHours').text().replace(/<br />/g, " ");
推荐答案
您的代码存在三个问题:
There are three issues with your code:
-
$('.WorkingHours').text()
将不包含任何HTML(因此也不包含任何br
标记),它仅返回元素的文本内容.
$('.WorkingHours').text()
返回:
$('.WorkingHours').text()
won't contain any HTML (so nobr
tags either), it only returns the text content of elements.
$('.WorkingHours').text()
returns:
M,W,Th,F 7:30 AM - 4:00 PMTu 7:30 AM - 6:00 PM
$('.WorkingHours').html()
返回:
M,W,Th,F 7:30 AM - 4:00 PM<br>Tu 7:30 AM - 6:00 PM<br>
您必须在表达式中转义内部的反斜杠. 编辑:查看.html()
的输出,实际上它不包含<br />
,但包含<br>
.这可能取决于文档的文档类型(无效的示例,
You have to escape the inner backslash in your expression. Having a look at the output of .html()
it actually does not contain <br />
but <br>
. This might depend on the doctype of the document (not working example, working example).
您必须将值分配回元素.
You have to assign the value back to the element.
您也许可以做到
$('.WorkingHours').html(function(i, html) {
return html.replace(/<br\s*\/?>/g, " ");
});
,但根本不使用正则表达式会更清洁:
but it would be much cleaner to not use regular expressions at all:
$('.WorkingHours').find('br').replaceWith(' ');
这将找到所有br
元素节点,并将它们替换为仅包含空格的文本节点.
This finds all br
element nodes and replaces them with a text node containing only a space.
更新(针对您的评论之一):如果要用句号替换最后一个br
,则可以使用.last()
:
Update (in response to one of your comments): If you want to replace the last br
with a full stop, you can use .last()
:
$('.WorkingHours')
.find('br').last().replaceWith('.')
.end().replaceWith(' ');
这篇关于使用其他javascript删除字符串中字符的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!