Please tell me about JavaScript regular expressions.

Asked 2 years ago, Updated 2 years ago, 16 views

Sample Code

 const path = 'index'; // index may be summary/product
constarray=['index']; // index may be summary/product

const result=array.find(page=>{
  if(page===path||`${page}/`===path){
    return page;
  }
})

As stated in the comment, the index portion of the variable path, array may be summary or product depending on the condition, which is a different condition for the variable array.
This is what happens.

Based on this, I have obtained result from the if statement as shown in the example. I would like to use regular expressions to get the same result. I would appreciate it if you could tell me how to write it.
(The reason for regular expressions is the assignment I gave myself as a part of my studies.)

In addition, the ${page}/ in the if statement is written in consideration of the trailing thrash.

I tried it for study, but I couldn't find out how to combine regular expressions to get the same results as this if statement, so I was ashamed to ask you this question.

In the first place, I am not sure if it is possible to use regular expressions, but I would appreciate it if someone could borrow your knowledge.

Thank you for your cooperation.

javascript

2022-09-29 22:14

1 Answers

Although you may have misunderstood what you actually want to do because you use the sample code find, the function argument given to find must return a true value (usually true or false.Even if you return a string, it will convert it to a true value, but you shouldn't write it in such a strange way.

const result=array.find(page=>page===path||`${page}/`===path);

So, let's move on with the assumption that path exactly matches page or page exactly matches '/'.

To say that a particular character or pattern does not matter, you can use ? in the regular expression, so you can modify it as follows:

const result=array.find(page=>{
    varpageRegex = newRegExp(page+'/?');
    return pageRegex.test(path);
});

If the page contains special characters as regular expressions, we have to escape that part, but the comments in the question have simplified it as unnecessary.

As you can see if you try, the value of result should be 'index' or 'index/'.

 const path='index/';//index may be summary/product
constarray=['index']; // index may be summary/product
const result=array.find(page=>{
    varpageRegex = newRegExp(page+'/?');
    return pageRegex.test(path);
});
console.log(result);

If you misunderstand or are unsure of the intent of your question, please let us know by editing the question itself or by commenting on this answer.


2022-09-29 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.