...

View Full Version : Replace up to specific character in URL - javascript



bluetitan
12-05-2009, 04:36 PM
Greetings,

I am having trouble finding any examples to help me strip everything up to a certain character (the hypen) in a url.

Hypothetical example below, as I only know how to accomplish this using a literal only for one url at a time but I need this for changing urls:



<script language="JavaScript"><!--
var temp = new String('http://www.site.com/abc_123_abc_-1379820930');
temp = temp.replace("http://www.site.com/abc_123_abc_-", '');
document.write(temp);
//--></script>

And I am hoping to be left with the series of numbers on the end. Any help is greatly appreciated. :thumbsup:

abduraooft
12-05-2009, 04:46 PM
You could combine indexOf() (http://www.w3schools.com/jsref/jsref_IndexOf.asp) with substr() (http://www.w3schools.com/jsref/jsref_substr.asp)

Philip M
12-05-2009, 06:45 PM
Or use a regex:-


<script type = "text/javascript">
var temp = new String('http://www.site.com/abc_123_abc_-1379820930');
temp = temp.replace(/[\w\W]+\-/g,"");
alert (temp);
</script>

<script language=javascript> is long deprecated and obsolete. Use <script type = "text/javascript"> instead.
The <!-- and //--> comment (hiding) tags have not been necessary since IE3. If you see these in some published script it is a warning that you are looking at ancient and perhaps unreliable code.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems." Jamie Zawinski.

bluetitan
12-06-2009, 05:45 AM
Awesome, thats exactly what I was looking for. :D

Thanks for the additional info about the deprecated code structures as well, I have never thought twice about it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum