最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - JavaScript: Search string from position - Stack Overflow

programmeradmin3浏览0评论

JavaScript has two useful methods, both which nearly do what I need.

  • String.prototype.indexOf() will search for a substring and return its position. It has an optional position parameter which is the starting point of the search, so you can easily find the next one.
  • String.prototype.search() will search a string using a regular expression and return its position. However, as far as I can tell, it doesn’t allow a starting position, so it always searches from the start.

Is there anything which allows me to find the position using a regular expression which does allow for a starting position?

JavaScript has two useful methods, both which nearly do what I need.

  • String.prototype.indexOf() will search for a substring and return its position. It has an optional position parameter which is the starting point of the search, so you can easily find the next one.
  • String.prototype.search() will search a string using a regular expression and return its position. However, as far as I can tell, it doesn’t allow a starting position, so it always searches from the start.

Is there anything which allows me to find the position using a regular expression which does allow for a starting position?

Share Improve this question asked Aug 1, 2022 at 8:52 ManngoManngo 16.6k13 gold badges104 silver badges148 bronze badges 1
  • You need this for a specific pattern only, or for "dynamic" ones? If the former - you could simply "prefix" it with ^[^]{x}, x being the number of characters you want to "skip". – C3roe Commented Aug 1, 2022 at 9:07
Add a ment  | 

3 Answers 3

Reset to default 4

You could do a String#slice in advance to get rid of unwanted parts and then take String#search.

function search(string, regexp, from = 0) {
    const index = string.slice(from).search(regexp);
    return index === -1
        ? -1
        : index + from;
}

The other answer is the way to go as its much clearer what the intention is, but if you had to use a regular expression, you could do it like this:

// This string should not include characters that have special
// meaning in regular expressions / should be escaped.
const inputString = "foo bar baz bar";
const offset = 8;
const searchString = "bar";
inputString.search(new RegExp(`(?=.{${offset}}${searchString}`));

//  (?=             make sure ${searchString} ("bar") 
//                  is preceded by:
//  .               anything
//  {$(a number)}   at least this many times:
//                  {8} in this example.

// The (?=A)B positive lookahead won't be included in the result,
// so you don't need to plus or minus the offset from the result:

// Example:
const str = 'aabbcc aabbcc aabbcc';
               ^      ^      ^
               2      9      16

str.search(new RegExp(`(?<=.{${0}})bb`));
// Return 2

str.search(new RegExp(`(?<=.{${4}})bb`));
// Returns 9

str.search(new RegExp(`(?<=.{${10}})bb`));
// Returns 16

str.search(new RegExp(`(?<=.{${1000}})bb`));
// Returns -1

str.search(new RegExp(`(?<=.{${10}})doesntexist`));
// Returns -1

In order to get the position of the original position of the search result you could use Nina Scholz' approach and then re-add the characters removed from the start. For Instance:

const str = "Hello World!";
let start = 5;
const output = str.substring(start).search(/World/g) + start;
console.log(output); //6

Note: Be careful with cases where .search() returns -1.

发布评论

评论列表(0)

  1. 暂无评论