-2

How do I find a string start and end position from a string. Is there a way to search the "m" and "g" coordinats or char position? given that there maybe multiple values. so far only upto start.

Find: myname.jpg

<img src="myname.jpg" id="men">


var start = x.indexOf("myname.jpg");
//10
Boy
  • 582
  • 1
  • 5
  • 22

1 Answers1

0

You can use a combination of .indexOf() and .substr().

When there is a possibility of multiple matches, providing more context characters to .indexOf() can resolve the issue or you can use .lastIndexOf() to start the search from the end of the string. You can also pass regular expressions to many of the string related methods and that is probably the best solution for extracting the correct positions based on some search criteria.

var x = "thewholestring";

// Get position where "whole" starts
var start = x.indexOf("whole");

// Extract 5 characters starting at that position
var result = x.substr(start, 5);

console.log(result);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71