使用JavaScript删除标记之间的每个空格

使用JavaScript删除标记之间的每个空格

本文介绍了使用JavaScript删除标记之间的每个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除标记之间的空白区域,以便childNodes仅包含那些标记节点,而不包含空白节点。这是我的代码:

I'm trying to remove white space between tags so that childNodes only contain those tags nodes not the white space nodes too. Here's my code :

<li>
    <label for="firstName"  class="mainLabel">First Name : </label>
    <input type="text" name="firstName" id="firstName"/>
    <span>This must be filled</span>
</li>

这里是JS代码:

var parentHTML = firstName.parentNode.innerHTML;
parentHTML = parentHTML.replace(/>\n</g,"><");
firstName.parentNode.innerHTML = parentHTML;

但当我提醒 parentHTML 我得到了相同的旧字符串。

But when i alert parentHTML i get the same old string.

推荐答案

它是(不是,请参阅规则之后)因为字符串是不可变的,我想,你是将parent元素的innerHTML设置为您之前从中检索的完全相同的字符串。

It's (not, see after the rule) because strings are immutable, I think, and you're setting the innerHTML of the parent element to be the exact same string you retrieved from it earlier.

相反,我建议:

var firstname = document.getElementsByTagName('input')[0],
    parentHTML = firstname.parentNode.innerHTML,
    newHTML = parentHTML.replace(/\>\s+\</g,'');
firstname.parentNode.innerHTML = newHTML;

console.log(parentHTML, newHTML, (parentHTML == newHTML));

关于来自jfriend00(下方)的评论,似乎是正则表达式是问题, \ n 与提供的模式不匹配,在这种情况下,以下修订符合要求:

With regards to the comment from jfriend00 (below), it seems the regular expression was the problem, the \n didn't match the supplied pattern, that being the case, the following amendment satisfies teh requirements:

var firstname = document.getElementsByTagName('input')[0],
    parentHTML = firstName.parentNode.innerHTML;
parentHTML = parentHTML.replace(/>\s+</g, "><");
firstName.parentNode.innerHTML = parentHTML;

console.log(firstname, parentHTML);​

参考文献:



  • JavaScript Regular Expressions.

这篇关于使用JavaScript删除标记之间的每个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:38