Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 正则表达式(Javascript)允许忽略逗号(regex (Javascript) allow comma to be ignore)

const value = 'I am a student. My age is 5';
const regex = new RegExp('\b' + value, 'i'); //what to add here?

console.log(regex.test('I am a student, my age is 5')); //true
console.log(regex.test('I am a student my age is 5')); //false

I want to ignore the , to make my second string to true.(我想忽略,使第二个字符串为true。)

  ask by Jennifer translate from so

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

1 Reply

0 votes
by (71.8m points)

you probably want a more generic regex like this:(您可能想要这样的通用正则表达式:)

const regex = /^I am a w+[.,]? My age is d+$/i console.log(regex.test('I am a student, my age is 5')); //should be true console.log(regex.test('I am a student my age is 5')); //should be true console.log(regex.test('I am a INSERTWORD my age is 5')); //should be true console.log(regex.test('I am a student my age is 230')); //should be true a less genric regex could look like this:(不太通用的正则表达式可能如下所示:) const regex = /^I am a student[.,]? My age is 5$/i console.log(regex.test('I am a student, my age is 5')); //should be true console.log(regex.test('I am a student my age is 5')); //should be true console.log(regex.test('I am a INSERTWORD my age is 5')); //should be false console.log(regex.test('I am a student my age is 230')); //should be false if you want to learn more about regexes go to one of:(如果您想了解有关正则表达式的更多信息,请访问以下任一:) https://regex101.com/ regex 101 is my go to regex testing website.(https://regex101.com/ regex 101是我去regex测试的网站。) https://www.regextester.com/(https://www.regextester.com/) https://regexr.com/(https://regexr.com/)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...