homepage Welcome to WebmasterWorld Guest from 54.225.1.70
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Getting a part of a string in JS
Kronos




msg:1471056
 3:09 pm on Jul 29, 2003 (gmt 0)

Hi,

I'm kind of new to JavaScript and I'm looking for a way to get, let's say, the characters from position 4 to position 9 in a string. Is there an easy way to do that? Thanks!

 

korkus2000




msg:1471057
 3:16 pm on Jul 29, 2003 (gmt 0)

var text1="string to process";
var whatever = text1.substring(3, 9);

Use the string object and the substring method. First number is where it starts, remember javascript starts at 0, and the second number is where it starts but does not include that character.

here is a example page that may help:

<html>
<head>
<title>Untitled</title>
<script>
function trimS(){
var text1=document.form1.textbox1.value;
var showMe = text1.substring(1, 4);
document.form1.textbox2.value=showMe;
}
</script>
</head>
<body>
<form name="form1" onSubmit="trimS(); return false">
<input type="text" name="textbox1">
<input type="submit">
<input type="text" name="textbox2">
</form>
</body>
</html>

Kronos




msg:1471058
 6:17 pm on Jul 29, 2003 (gmt 0)

It worked! I thought that I'd seen it before, but I wasn't sure. Thanks Korkus!

MonkeeSage




msg:1471059
 12:59 am on Aug 4, 2003 (gmt 0)

I use the substring() method almost exclusivley over substr() or slice().

Substring can be used to get from a start char to the end of the string also, by just passing it the start char, i.e., string.substring(4); will get from char 4 to string.length.

The other thing I use it for alot is to snip out or replace known sections of an unparsed string, i.e., var a = string.substring(0, string.indexOf("example")); var b = string.substring(string.indexOf("example") + "example".length); string = a + "this used to say 'example'" + b;

Jordan

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved