0

I come from C++ background and currently working on node.js server app. I want to know if there exists an equivalent of find_first_of C++ string class method in Javascript string.

Basically I'll have a string like var str ="abcd=100&efgh=101&ijkl=102&mnop=103". The order of & seprated words could be random. So, I wanted to do something like the following:

str.substr(str.find("mnop=") + string("mnop=").length, str.find_first_of("&,\n'\0'")

Is there a way to it in a single line like above?

Alex Filatov
  • 2,128
  • 3
  • 32
  • 37
ak47Masker
  • 11
  • 1

2 Answers2

0

You may find the search function useful.

"string find first find second".search("find"); // 7

In addition, you may also find this question useful.

Community
  • 1
  • 1
php_nub_qq
  • 13,981
  • 19
  • 68
  • 133
0

There's no direct equivalent, but you always can employ regular expressions:

var str ="abcd=100&efgh=101&ijkl=102&mnop=103";
console.log(str.match(/&mnop=([^&]+)/)[1]);

However, in this specific case, it's better to use the dedicated module:

var qs = require('querystring');
var vars = qs.parse(str);
console.log(vars.mnop);

If you really want a method that behaves like find_first_of, it can be implemented like this:

String.prototype.findFirstOf = function(chars, start) {
    var idx = -1;
    [].some.call(this.slice(start || 0), function(c, i) {
        if(chars.indexOf(c) >= 0)
            return idx = i, true;
    });
    return idx >= 0 ? idx + (start || 0) : -1;
}

console.log("abc?!def??".findFirstOf('?!'));    // 3
console.log("abc?!def??".findFirstOf('?!', 6)); // 8
georg
  • 204,715
  • 48
  • 286
  • 369