简体   繁体   中英

JavaScript string.replace: inserting text as HTML

I'm trying prepend all semicolons in a string with the HTML character   , which is a non-breaking thin space.

To do this, I have written this line:

str = str.replace( /;/g, " ;" );

Unfortunately, the thin space character is written in directly, instead of its HTML representation.

Is there a flag, a setting or even another function that will allow me to insert this character as HTML?

Thank you.

Edit: Probably should have mentioned this before: I'm working on a basic pseudocode-to-HTML converter, in which certain characters in the original string are replaced by their standard HTML equivalents.

The resulting string is then output to a div element, where I can inspect it to make sure it looks good. I then retrieve the source of this new text to place into some other web page.

But when I look at the source for the thin space, it's just the character itself, not the entity name.

(I'd paste the full source for the conversion, but it's over 300 lines.)

Edit 2: I was under the impression that Ctrl+U in Firefox would show the newly added characters. My mistake; they only appear when when viewing the source with Firebug (or its Webkit equivalent), or selecting the text, right-clicking and viewing the source for the selection (option only available in FF, it seems).

To test the latter approach, I created two div elements and used this JavaScript code:

document.getElementById( "div1" ).innerHTML = ( "'&'" );
document.getElementById( "div2" ).innerHTML = ( "' '" );

The ampersand is displayed as & , but the thin space's entity name is not used. This might just be weird behavior from this specific FF feature.

If you literally want the characters   , the ampersand has to be encoded as such.

str = str.replace( /;/g, " ;" );

Why do you have the second semicolon in your replacement? Shouldn't it just be:

str = str.replace( /;/g, " " );

On my client 'str' contains the HTML entities but once you attach it to the DOM then the entities are changed into native characters. I guess it depends on what you're using it for. If you use 'str' as the innerText of an element then you'll see the entities and not the space. eg

(function(s) { var x=document.createElement('div'); x.innerText=s; document.body.appendChild(x); })(str);

" " is an html entity and therefore not understood by javascript. I recommend using the String.fromCharCode() method. An example would be as follows...

var str = 'test;here';

str = str.replace( /;/g, String.fromCharCode(8239) );

alert(str);

You can learn more about the fromCharCode method here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM