Home > Software engineering >  How would you find if a string contains a substring exactly with non-alphanumeric in nodeJS?
How would you find if a string contains a substring exactly with non-alphanumeric in nodeJS?

Time:11-17

I was trying to design something that sees if a string contains exactly another substring, and they contain non-alphanumeric

For example:

const subStr = '#320';
const str1 = '#320 people';
const str2 = '#3202 people';
const str3 = "1#3202 people';

str1 should match because it contains exactly #320 str2 should not match because it contains an extra 2 at the end str3 should not match because it contains an extra 1 at the front

I can't seem to figure something out that works

CodePudding user response:

Just base on your input, I write this very ugly solution but it works anyway:

const subStr = '#320';
const str1 = '#320 people';
const str2 = '#3202 people';
const str3 = '1#3202 people';

const filter = (target, condition) => (` ${target} `.includes(` ${condition} `));

console.log(filter(str1, subStr)); // true
console.log(filter(str2, subStr)); // false
console.log(filter(str3, subStr)); // false

CodePudding user response:

Assuming what you really want is #320 with either whitespace, newline or begin or end of string before/after it, then you can accomplish that with a regex.

const testStrings = [
    '#320 people',
    '   #320 people',
    '#3202 people',
    '1#3202 people',
    'Other stuff #320 people',
    'Other line\n#320 people',
    'people #320',
    'people #320\n'
];

const regex = /(^|\s)#320(\s|$)/m;

for (let str of testStrings) {
    const match = regex.test(str);
    const matchStr = match ? "matches  " : "no match "
    console.log(`${matchStr}: "${str}"`);
}

  • Related