Code Help in Regex

ST9
Tera Contributor

Hi All,

I wanted to extract a Order Number(123456789) and save that text to a particular custom field. if the order number is empty the, the custom field should be empty as well.

Example this- 

Order Number: 123456789
Candidate Name: Albert Test
Profile link: check

Hello

First Advantage is conducting a background check..

How do i achieve this using regex or any other way?

var des= current.description;
var index = des.indexOf("Order Number:");
var orderNum = des.substring(index+14, index+23);
	current.u_order_number= orderNum;

 

1 ACCEPTED SOLUTION

Hi @ST9 ,

You can modify the regular expression pattern and use the ^ and $ anchors.

Here's an updated example:

 

var des = current.description;
var orderNumRegex = /^Order Number:\s*([A-Za-z0-9]+)$/m;
var match = orderNumRegex.exec(des);
var orderNum = match ? match[1] : '';
current.u_order_number = orderNum;

 

In the updated code:

  • The ^ anchor at the beginning of the pattern ensures that the match starts at the beginning of a line.
  • The $ anchor at the end of the pattern ensures that the match ends at the end of a line.
  • The m flag is used after the closing / to enable multi-line mode so that ^ and $ match the beginning and end of each line in the input string.

 

If my response was helpful in resolving the issue, please consider accepting it as a solution by clicking on the Accept solution button and giving it a thumbs up 👍. This will benefit others who may have a similar question in the future.

 

Thank you!

Ratnakar

View solution in original post

11 REPLIES 11

ST9
Tera Contributor

Hi @Ratnakar7 :
The above code does not work if there is space before the order number
Example-
 

 Order Number: 123
Candidate Name: THOMAS BERNIER
Profile link:
Hello

 

Could you please help?

Hi @ST9 ,

You can modify the regular expression pattern to include optional spaces before the number. Here's an updated code snippet that should work:

 

var des = current.description;
var orderNumRegex = /^\s*Order Number:\s*([A-Za-z0-9-]+)/m;
var match = orderNumRegex.exec(des);
var orderNum = match ? match[1] : '';
current.u_order_number = orderNum;

 

 

In this updated code, \s* allows for zero or more spaces.

 

Thanks,

Ratnakar