javascript - getElementById replace HTML -
<script type="text/javascript"> var haystacktext = document.getelementbyid("navigation").innerhtml; var matchtext = '<a href="http://mydomain.co/?feed=rss">subscribe rss</a>'; var replacementtext = '<ul><li>some other thing here</li></ul>'; var replaced = haystacktext.replace(matchtext, replacementtext); document.getelementbyid("navigation").innerhtml = replaced; </script>
i'm attempting try , replace string of html code else. cannot edit code directly, i'm using javascript alter code.
if use above method matching text on regular string, such just 'subscribe rss', can replace fine. however, once try replace html string, code 'fails'.
also, if html wish replace contains line breaks? how search that?
<ul><li>\n</li></ul>
??
what should using or doing instead of this? or missing small step? did search around here, maybe keywords search weren't optimal find result fit situation...
edit: gonna mention, i'm writing script in footer of page, after text wish replace, it's not issue of script being written before want overwrite appear. :)
currently using string.replace(substring, replacement)
search exact match of substring
, replace replacement
e.g.
"hello world".replace("world", "kojichan") => "hello kojichan"
the problem exact matches doesn't allow else exact matches.
to solve problem, you'll have start use regular expressions. when using regular expression have aware of
- special characters such
?
,/
, ,\
need escaped\?
,\/
,\\
- multiline mode /regexp/m
- global matching if want replace more 1 instance of expression /regexp/g
- closures allowing multiple instances of white space
\s+
[1..n] white-space characters ,\s*
[0..n] white-space characters.
to use regular expression instead of substring matching need change string.replace("substring", "replacement")
string.replace(/regexp/, "replacement")
e.g.
"hello world".replace(/world/, "kojichan") => "hello kojichan"
Comments
Post a Comment