3

I am starting to learn a little bit more advanced js and i want to check if string contains a word at the start of the line. Something like this would be good!:

var string = "Hello world";
if (string.contains("Hello", start) == true)
{
console.log("success");
}

3 Answers3

6

Very easy Method:

var str = "Hello World";

if (str.startsWith("Hello")){
    do stuff;
}

You could also make two arrays and compare the single letters using a for loop, slightly more creative :D

marcb20012
  • 73
  • 5
1
if (fullString.substring(0, stringToFind.length) == stringToFind) {

}
Danny Buonocore
  • 3,731
  • 3
  • 24
  • 46
1

In ES6, you can use startsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith.

Otherwise you can use RegExp with '^' which matches the beginning of input (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) like this: /^Hello/.test('Hello World')

willywonka
  • 117
  • 5