A. W.
A. W.

Reputation: 671

Why lastIndexOf() works and search() does not?

I was trying my hand at editing a given string to remove the file extension at the end by using a combination of slice() and search(). However, when using search(), the var vNamePrepared would come up empty.

function site_change() {
  var vDocGrabber = "indexmobile.html",
      vNamePrepared = vDocGrabber.slice(0, vDocGrabber.search("."));
  /*transform vNamePrepared in some way*/
  document.getElementById("demo").innerHTML = vNamePrepared + ".php";}

Alternatively, that exact code with search() replaced by lastIndexOf() produced the desired result.

function site_change() {    
  var vDocGrabber = "indexmobile.html",
      vNamePrepared = vDocGrabber.slice(0, vDocGrabber.lastIndexOf("."));
  /*transform vNamePrepared in some way*/
  document.getElementById("demo").innerHTML = vNamePrepared + ".php";}

--> indexmobile.php

For what reason would search() not work here? Would it not return the index of the period as an integer into slice()?

First question, apologies if it's not up to standard.

Upvotes: 0

Views: 96

Answers (3)

Nix
Nix

Reputation: 176

It is processing the "." as a regex.

To escape the ".":

vDocGrabber.search('\\.')

Upvotes: 2

Sam Ccp
Sam Ccp

Reputation: 1162

Personally I never use .search method since i've come up with bugs on different browsers

Instead i rely upon .indexOf since it has better support, here's a little help from the infamous w3 site

Upvotes: -3

Ry-
Ry-

Reputation: 224867

search accepts a regular expression, and . matches any non-newline character in a regular expression. The equivalent to lastIndexOf starting from the beginning is indexOf.

Upvotes: 5

Related Questions