Skip to content Skip to sidebar Skip to footer

How To Determine Whether String Is Code-method?

I explain my question via 2 examples: Example1: var str1 = 'this is a test this is a test'; I want this: this is not code-method Example2: var str2 = ' this is

Solution 1:

The regex /\n?\s+/gm will select the lines that have one or more spaces at the beginning. You need to check if the line starts with four spaces.

You can use

/^ {4}/gm

RegEx Explanation

  1. ^: Start of line
  2. {4}: Match four spaces
  3. gm: Global and multiline flag

// RegEx
var linebreak = /\r\n|\r|\n/g,
    coded = /^ {4}/gm;

function isCoded(str) {
  return str.split(linebreak).length === (str.match(coded) || []).length;
}

var str1 = `    this is a test
                this is a tes`,
    str2 = ` this is test
    not coded`;

document.body.innerHTML = str1 + ': is-coded? ' + isCoded(str1) + '<br />' + str2 + ': is-coded? ' + isCoded(str2);

Solution 2:

Something like

> str1.split(/\r|\r\n|\n/).length == str1.match(/^\s{4,}/gm).length
< false

and

> str2.split(/\r|\r\n|\n/).length == str2.match(/^\s{4,}/gm).length
< true

Solution 3:

You'll need to return a boolean if you want to work out whether a string is valid or not.

You can split the string on newlines, then use the every method with a predicate function to test that each line meets your criteria.

function isCodeMethod(string) {
  const hasIndent = /^\s{4}/;
  return string
    .split("\n")
    .every(s => hasIndent.test(s));
}

With some test input.

// false
isCodeMethod("this is a test")

// true
isCodeMethod("    this is a test")

// false
isCodeMethod(`    this is a test1
this is a test2`)

// true
isCodeMethod(`    this is a test1
this is a test2`)

// true
isCodeMethod(`    this is a test1
                  this is a test2`)

Post a Comment for "How To Determine Whether String Is Code-method?"