0

Python startswith() allows me to test if a string starts with a tuple of strings as shown below, which is what I want to achieve with JavaScript:

testvar = 'he', 'hi', 'no', 'ye'
if my_string.startswith(testvar):
    return True

I have seen this SO question and it did not completely help in achieving this.

I need to have a JavaScript code that will do the same thing with the Python code above.

Community
  • 1
  • 1
Yax
  • 2,127
  • 5
  • 27
  • 53

5 Answers5

2

Since there has been many solutions for having an array passed as argument, I am gonna post a solution splat "*" style arguments:

String.prototype.startsWithSplat = function(){ 
  var args = Array.prototype.slice.call(arguments, 0, arguments.length); 
  var i;
  var matched = false;
  var self = this;
  for(i = 0; i < args.length; i++){
    if(self.slice(0, args[i].length) == args[i]){
      matched = true;
      break;
    }
  }
  return matched;
}

Then you can just call:

my_string.startswith('he', 'hi', 'no', 'ye');
1

All you need is a simple loop over an Array with one of the answers shown there,

var testvar = ['he', 'hi', 'no', 'ye'];

function startsWith2(haystack, needles) {
    var i = needles.length;
    while (i-- > 0)
        if (haystack.lastIndexOf(needles[i], 0) === 0)
            return true;
    return false;
}

startsWith2('hello world', testvar); // true
startsWith2('foo bar baz', testvar); // false

Similarly for endsWith;

function endsWith2(haystack, needles) {
    var i = needles.length, j, k = haystack.length;
    while (i-- > 0) {
        j = k - needles[i].length;
        if (j >= 0 && haystack.indexOf(needles[i], j) === j)
            return true;
    }
    return false;
}
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Since they're all the same length you could just do:

testvar = ['he', 'hi', 'no', 'ye']
return testvar.indexOf(my_string.substring(0,2)) > -1

And some examples:

// Examples:
testvar = ['he', 'hi', 'no', 'ye']
my_string = 'hello'
testvar.indexOf(my_string.substring(0,2)) > -1
true

my_string = 'apples'
testvar.indexOf(my_string.substring(0,2)) > -1
false
JBux
  • 1,394
  • 8
  • 17
0

You can run a reduce operation over your array of tests to find if a variable starts with any of them.

var testVar = ['he', 'hi', 'no', 'ye'];
var myString = 'hello';

var startsWithAny = testVar.reduce(function (returnValue, currentTest) {
  return returnValue || myString.startsWith(currentTest);
});

if (startsWithAny) {
  return true;
}
Zachary Kuhn
  • 1,152
  • 6
  • 13
0
var testvar = ['he','hi','no','ye'];
var str = "hello";

for(i = 0; i < testvar.length; i++)
{
   if (str.startsWith(testvar[i]) == true)
            console.log(str+" starts with: "+testvar[i]);
}
FirebladeDan
  • 1,069
  • 6
  • 14