How 2 get a substring from a string?

J

Jean-Guy Mouton

Hello,

I am teaching myself Dom scripting with Javascript. I do not understand
how to get a substring. If I have strings in the form:
"This is string number 1"
How can I put "1" into a variable to use it elsewhere? I thought I
could use the function split and create an array but I have different
string lengths with a variable number of words...
Can you please help me? Thank you.
 
T

Thomas 'PointedEars' Lahn

Jean-Guy Mouton said:
I am teaching myself Dom scripting with Javascript. I do not understand
how to get a substring. If I have strings in the form: "This is string
number 1" How can I put "1" into a variable to use it elsewhere?

var one = s.match(/\d+/)[0];
I thought I could use the function split and create an array but I have
different string lengths with a variable number of words...

So?

var
a = s.split(/\s/),
lastWord = a[a.length - 1];


PointedEars
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>,
I am teaching myself Dom scripting with Javascript. I do not
understand how to get a substring. If I have strings in the form:
"This is string number 1"
How can I put "1" into a variable to use it elsewhere? I thought I
could use the function split and create an array but I have different
string lengths with a variable number of words...
Can you please help me? Thank you.


There are several ways of doing that, depending on how you want to
define the desired extraction.

You might want the 23rd character, or all characters after the 22nd, or
the last character, or the character after the 4th space, or the 5th
"word", or the first set of consecutive octal digits, or the last set of
consecutive decimal digits, etc.

Seek a reference such as <http://developer.mozilla.org/en/docs/Core_Java
Script_1.5_Reference>, and look for appropriate properties of String,
such as charAt, match, substring and substr.

In most cases, at least, one can use a RegExp search; but it may well
not be necessary,

Alternatively, you've used the words Javascript and substring - search
the Web, and you'll soon find references, some being good.

The reference at sussex.ac.uk, though old, is good; and should appear
(unlike most) in your favoured font face and size. I frequently use a
local copy of what it is a copy of.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top