Thursday, 15 January 2015

javascript - Replace words of text area -



javascript - Replace words of text area -

i have made javascript function replace words other words in text area, doesn't work. have made this:

function wordcheck() { var text = document.getelementbyid("ec").value; var newtext = text.replace(/hello/g, '<b>hello</b>'); document.getelementbyid("ec").innertext = newtext; }

when alert variable newtext, console says variable doesn't exist. can help me?

edit: replace words, replaces <b>hello</b>, want have bold. there solution?

if <textarea>, need utilize .value property.

document.getelementbyid("ec").value = newtext;

and, mentioned barmar, replace() replaces first word. replace word, need utilize simple regex. note removed quotes. /g means global replace.

var newtext = text.replace(/hello/g, '<b>hello</b>');

if want bold text, need utilize content editable div, not text area:

<div id="ec" contenteditable></div>

so need access innerhtml:

function wordcheck() { var text = document.getelementbyid("ec").innerhtml; var newtext = text.replace(/hello/g, '<b>hello</b>'); newtext = newtext.replace(/&lt;b&gt;&lt;b&gt;/g,"&lt;b&gt;");//these 2 lines there prevent <b><b>hello</b></b> newtext = newtext.replace(/&lt;\/b&gt;&lt;\/b&gt;/g,"&lt;/b&gt;"); document.getelementbyid("ec").innerhtml = newtext; }

javascript regex replace words

No comments:

Post a Comment