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
533 views
in Technique[技术] by (71.8m points)

jquery - Replacing tab characters in JavaScript

Please consider the following HTML <pre> element:

This is some  
example code which    
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;contains tabs

I would like to replace all of the tab characters with four non-breaking space characters in HTML (i.e. &nbsp;). I have tested the above pre element with JavaScript for the presence of tab characters as follows:

$('pre').ready(function() {
    alert(//.test($(this).text()));
});

But it is always returned false. Can anyone tell me the correct process by which to replace tab spaces from the source code to HTML NBSPs? The tabs have been added by Komodo Edit, and are visible when viewing the source.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can do it like this:

$('pre').html(function() {
    return this.innerHTML.replace(//g, '&nbsp;&nbsp;&nbsp;&nbsp;');
});

That will loop through all pre elements on the page and call the function for each of them. jQuery's html function uses the return value of the function we give to replace the content of each element. We're using String#replace to replace all (note the g flag on the regexp) tab characters in the HTML string with four non-breaking spaces.

Live example


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

...