0

I'm actually new in JavaScript. I'm currently work on string matching. I can understand why it is usable and so on however whenever I'm trying to make it dynamic my output is 'null' for some reason.

function matchString(str, match) {
    let result = str.match('/' + match + '/g');
    console.log('Output: ' + result);
}

matchString('Hello Stack Overflow', 'over'); // null

function matchString(str, match, para) {
    let result = str.match('/' + match + '/' + para);
    console.log('Output: ' + result);
}

matchString('Hello Stack Overflow', 'over', 'g'); // null

I want it to output 'Over' in my console

1 Answers1

0

Couple of things you have to change:

  • For dynamic pattern use RegExp
  • over Vs Over is another thing. Make it case insensitive by using i

Here is your modified code:

// With RegExp, case insensitive
function matchString1(str, match) {
    let result = str.match(new RegExp(match, 'ig'));
    console.log('Output: ' + result);
}
// With RegExp, case insensitive
function matchString2(str, match, para) {
    let result = str.match(new RegExp(match, para));
    console.log('Output: ' + result);
}
// Without RegExp, case sensitive
function matchString3(str, match) {
    let result = str.match(match);
    console.log('Output: ' + result);
}

matchString1('Hello Stack Overflow', 'over');
matchString2('Hello Stack Overflow', 'over', 'ig');
matchString3('Hello Stack Overflow', 'Over');
fiveelements
  • 3,649
  • 1
  • 17
  • 16