'JavaScript - check if string starts with

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

How can i accomplish this?



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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

Solution 4:[4]

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

Solution 5:[5]

It's 2022 and startsWith has great support

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

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

Solution 6:[6]

var str = "abcd";

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

Solution 7:[7]

<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" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 David G
Solution 3 KooiInc
Solution 4
Solution 5 Félix Paradis
Solution 6 David G
Solution 7