javascript substring match code example

Example 1: check for substring javascript

const string = "javascript";
const substring = "script";

console.log(string.includes(substring));  //true

Example 2: check if word is in string javascript

var str = "Hello world, welcome to the universe.";
var n = str.includes("world");

Example 3: javascript contains substring

var str = "We got a poop cleanup on isle 4.";
if(str.indexOf("poop") !== -1){
	alert("Not again");
}
//use indexOf (it returns position of substring or -1 if not found)

Example 4: match substring js

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

Example 5: .includes( string

var str = "Hello world, welcome to the universe.";
var n = str.includes("world");

Example 6: how to use the match function in javascript for regex

const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);

console.log(found);

// logs [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]

// 'see Chapter 3.4.5.1' is the whole match.
// 'Chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'.
// '.1' was the last value captured by '(\.\d)'.
// The 'index' property (22) is the zero-based index of the whole match.
// The 'input' property is the original string that was parsed.

Tags:

Cpp Example