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

12-05-2009, 05:36 PM

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_-", '');

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

12-05-2009, 05: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, 07: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 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.

12-06-2009, 06: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