2

How can I use String.prototype.indexOf() to find one or more matching string patters within a given string?

For example:

  • I have a string to test: /accounts/{account}/project/{project}

  • I want to test for the existence of one or more string patterns of {...} where ... could have anything. In this example they are: account, project

  • I would like to String.prototype.indexOf() to retrieve an Object that has a collection of start and end indexes for each instance of the matched pattern. In this example I would like to have: [{ start: 10, end: 18},{start: 28, end: 36}]

I've been able to make an object when there is just one match, but I am unsure how to get for multiple.

3
  • 1
    Please post what you have tried so far Commented Aug 16, 2019 at 14:45
  • Also, please elaborate on your objective. If you're trying to parse a URL on the server side (e.g., with Node.js), there may be built-ins that can do it for you (route parameters and req.params, for instance). Commented Aug 16, 2019 at 14:49
  • @IronFlare - Actually, route.parameters is what I am trying to accomplish. I was trying to make something myself to use client-side. I am probably over-complicating this instead of using what you suggested. I was just trying to see if I could make my own solution. Commented Aug 16, 2019 at 15:43

3 Answers 3

2

Using replace() method

var stringUnderTest = "/accounts/{account}/project/{project}"; var result = []; stringUnderTest.replace(/\{([^\}]*)\}/gi, function(match, p1, index) { result.push({ start: index, end: index + p1.length + 1 }) }); console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

indexOf only returns the first occurrence of a pattern in a string (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). You COULD override it with your own implementation that simply calls indexOf multiple times and stores the results in an array which it returns as its final result but this would be a bad idea as you'd be overriding the default implementation. A better approach would be to create a new prototype function (eg, String.prototype.indexOfMany).

Comments

0

I would go for String.prototype.match. (Documentation)

It returns all substrings that match a given regex.

For your example you might use something like this:

var stringUnderTest = "/accounts/{account}/project/{project}"; var foundStrings = stringUnderTest.match(/\{[a-z]*\}/gi); console.log(foundStrings);

This way you get all occurences of {...} whose positions you could then determine with indexOf.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.