Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

regex - Remove every white space between tags using JavaScript

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>   

And here's the JS code :

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Instead, I'd suggest:

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));

JS Fiddle demo.


With regards to the comment from jfriend00 (below), it seems the regular expression was the problem, the 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);?

JS Fiddle demo.

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...