使用其他javascript删除字符串中字符的所有实例 [英] remove all instances of a character in a string with something else javascript

查看:99
本文介绍了使用其他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:

  1. $('.WorkingHours').text()将不包含任何HTML(因此也不包含任何br标记),它仅返回元素的文本内容.
    $('.WorkingHours').text()返回:

  1. $('.WorkingHours').text() won't contain any HTML (so no br 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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆