Alosyius
Alosyius

Reputation: 9121

JavaScript - check if string starts with

I am trying to check if a string starts with the character: /

How can i accomplish this?

Upvotes: 6

Views: 22887

Answers (7)

Félix Paradis
Félix Paradis

Reputation: 6041

It's 2022 and startsWith has great support

let string1 = "/yay"
let string2 = "nay"

console.log(string1.startsWith("/"))
console.log(string2.startsWith("/"))

Upvotes: 4

Justin Niessner
Justin Niessner

Reputation: 245449

if(someString.indexOf('/') === 0) {
}

Upvotes: 21

Umair Saleem
Umair Saleem

Reputation: 1063

data.substring(0, input.length) === input

See following sample code

var data = "/hello";
var input = "/";
if(data.substring(0, input.length) === input)
    alert("slash found");
else 
    alert("slash not found");

Fiddle

Upvotes: 1

KooiInc
KooiInc

Reputation: 122936

Alternative to String.indexOf: /^\//.test(yourString)

Upvotes: 2

MackieeE
MackieeE

Reputation: 11872

<script>
   function checkvalidate( CheckString ) {
      if ( CheckString.indexOf("/") == 0 ) 
        alert ("this string has a /!");
   }
</script>

<input type="text" id="textinput" value="" />
<input type="button" onclick="checkvalidate( document.getElementById('textinput').value );" value="Checkme" />

Upvotes: 0

Amrendra
Amrendra

Reputation: 2077

var str = "abcd";

if (str.charAt(0) === '/')

Upvotes: 1

David G
David G

Reputation: 96835

Characters of a string can be accessed through the subscript operator [].

if (string[0] == '/') {

}

[0] means the first character in the string as indexing is 0-based in JS. The above can also be done with regular expressions.

Upvotes: 11

Related Questions