Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - How to compare a sentence by creating regular expressions except few chars in NodeJS?

I have a phrase:

let msg = "Dear XX,Thanks for visting XX"
let usermsg = "Dear sd dta,Thanks for visting ght hg"

I need to compare these two sentences, ignoring "XX" and "YY". How can I create a regular expression to compare both of these in Nodejs?

I have replaced "XX" with an empty space and tried whether the usermsg includes msg or not. But that doesn't work.

var separators = ['XX','YY'];
let dMsg = msg.split(new RegExp(separators.join('|'),'g'));
for (var p = 0; p < dMsg.length; p++) {       
    if (!(usermsg.includes(dMsg[p]))) {
        console.log("fail");
        break;
    }
}

It doesn't work if the user adds an extra string in front, like:

usermsg2 = "Hey Dear ghgh,Thanks for visting jkj",

In the above usermsg2, "Hey" should not be there, but my code returns that both are the same.

Kindly suggest how to check these?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could dynamically generate a regex from the split string.

This is a basic example which assumes you know the character length of each separator. If the separator is longer or shorter than two characters, it won't work:

const separators = ['XX', 'YY'];
const msg = "Dear XX,Thanks for visting XX"
const userMsg = "Hey Dear ghgh,Thanks for visting jkj"
const dMsg = msg.split(new RegExp(separators.join('|'), 'g'));
const regex = new RegExp(`^${dMsg.join('..')}$`)

console.log(regex)

if (!userMsg.match(regex)) {
  console.log("fail");
} else {
  console.log("success");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...