Natali
Natali

Reputation: 75

Check occurrence of element in string with Regex?

I have strings and some of them may contain

:
or
=
I would like to find all cases, where these symbols occurs, but only once(!).

I wrote this code, which works, but would like to solve with Regex expression

function find(stringToCheck: string): string {
    return stringToCheck.includes(':') &&
        stringToCheck.split(':').length - 1 === 1
        ? ':'
        : stringToCheck.includes('=') && stringToCheck.split('=').length - 1 === 1
        ? '='
        : '';
}

Upvotes: 0

Views: 150

Answers (3)

MonkeyZeus
MonkeyZeus

Reputation: 20747

You could use:

^[^:=]*[:=][^:=]*$

function checkString(str){
    return /^[^:=]*[:=][^:=]*$/.test(str);
}

console.log(checkString('Neither'));
console.log(checkString('One equal ='));
console.log(checkString('One colon :'));
console.log(checkString('colon equal :='));
console.log(checkString('Multiple = equal ='));
console.log(checkString('Multiple : colon :'));
console.log(checkString('Multiple = both : col=on :'));

Upvotes: 0

avasuilia
avasuilia

Reputation: 136

Try this:

function find (stringToCheck)
{
  return (/^[^:]*:[^:]*$/.test(stringToCheck) && /^[^=]*=?[^=]*$/.test(stringToCheck))||(/^[^:]*:?[^:]*$/.test(stringToCheck) && /^[^=]*=[^=]*$/.test(stringToCheck));
}

console.log(find("iron:man"));
console.log(find("iron=man"));
console.log(find("iron::man"));
console.log(find("iron==man"));
console.log(find("ironman"));

Upvotes: 1

LaytonGB
LaytonGB

Reputation: 1404

The string is searched for matches with : or = which are then stored as a RegExp match array. The length of this array then matches how many instances of the string were found.

Where the RexExp objects are created the flag "g" is used to find all matches, rather than just the first one.

function find (stringToTest) {
  const a = stringToTest.match(new RegExp(":", "g"));
  const b = stringToTest.match(new RegExp("=", "g"));
  if (a?.length > 1 || b?.length > 1) return true;
  return false;
}

console.log(find("hello:world=")); // false
console.log(find("hello world")); // false
console.log(find("hello world====")); // true

Upvotes: 1

Related Questions