Link to home
Start Free TrialLog in
Avatar of turtleman2009
turtleman2009

asked on

Javascript remove characters from string

The below code does not work but I need it to badly.  The problem is something with the inline javascipt if i use this code outside of the div and just use the normal <Script type="text/javascript"> tags it works fine.  

Any ideas or solutions for me, I would really appreciate it.
<div id="javascript:var str ="01/01/2009"; var newStr = str.substring(6);  
document.write( 'a' + newStr );"
 
the end result that i need outputted is just <div id="a2009"

Open in new window

Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

You have to put the Javascript in a script tag, but you can't have a script tag inside the attribute of an html tag, so you have to write all of the div tag using Javascript:
<script type="text/javascript">
var str = "01/01/2009";
var newStr = str.substring(6);
document.write('<div id="a' + newStr + '">');"
</script>

Open in new window

You cannot do it this way

one way is this



<div id="_div">
 
</div>
<script type="text/javascript"> 
var str ="01/01/2009"; var newStr = str.substring(6);  
var mydiv = document.getElementById("_div");
mydiv.id =  'a' + newStr ;
 
alert(mydiv.id);
</script>

Open in new window

Avatar of turtleman2009
turtleman2009

ASKER

Thanks for your help I didn't realize things would need to change that much. Additionally I had a class that needs to be changed to.  I have attached the full source, could someone please fix it for me

Could you please test your code to make sure it works I couldn't tell if they were doing what they needed to because when i viewed the source it just showed me the javascript

Thanks so much!
<div id="javascript:var str ="01/01/2009"; var newStr = str.substring(6);  
document.write( 'a' + newStr );" class="avascript:var str ="01/01/2009"; var newStr = str.substring(4);  
document.write( 'a' + newStr );">

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of quincydude
quincydude
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Perfect, this is just what i needed!
If you use FireBug in Firefox, it will show you both the script and the generated code.

Use the substr function instead of substring. It's an undocumented feature that substring can be used with only one parameter...
<script type="text/javascript">
var str = '01/01/2009';
document.write('<div id="a' + str.substr(6) + '" class="a' + str.substr(4) + '">');
</script>

Open in new window