MavrosGatos
MavrosGatos

Reputation: 529

Find substring position into string with Javascript

I have the following strings

"www.mywebsite.com/alex/bob/a-111/..."
"www.mywebsite.com/alex/bob/a-222/..."
"www.mywebsite.com/alex/bob/a-333/...".

I need to find the a-xxx in each one of them and use it as a different string. Is there a way to do this? I tried by using indexOf() but it only works with one character. Any other ideas?

Upvotes: 1

Views: 2319

Answers (3)

XiongZhiguo
XiongZhiguo

Reputation: 1

var reg=/a-\d{3}/;
text.match(reg);

Upvotes: 0

alok
alok

Reputation: 510

Use the following RegEx in conjunction with JS's search() API

/(a)\-\w+/g

Reference for search(): http://www.w3schools.com/js/js_regexp.asp

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

You can use RegExp

var string = "www.mywebsite.com/alex/bob/a-111/...";

var result = string.match(/(a-\d+)/);

console.log(result[0]);

or match all values

var strings = "www.mywebsite.com/alex/bob/a-111/..." +
  "www.mywebsite.com/alex/bob/a-222/..." +
  "www.mywebsite.com/alex/bob/a-333/...";

var result = strings.match(/a-\d+/g)

console.log(result.join(', '));

Upvotes: 4

Related Questions