Reputation: 9121
I am trying to check if a string starts with the character: /
How can i accomplish this?
Upvotes: 6
Views: 22887
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
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");
Upvotes: 1
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
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