Thursday, February 28, 2019

regex - Javascript to find number after character (colon)





I've looked at other answers to this question, as there have been similar ones before, but I just can't get it work. I'm new to javascript, so please be kind.



From the body of an email, I need to find a phrase that will end with "number:" followed by a number.



e.g. Sample Email Body:



...  
customer reference number: 123456
or
site reference number : 827893

...


then that reference number '123456' or whatever it is, needs to be a variable/value I'll use elsewhere.



I don't want anything before the number, and I don't want anything after the number (eg. the next lines).



Tried this:



var str  = "reference number: 1234";

var RefStr = str.match(/number\:\s+(\d+)$/i)


But it returns number: 1234.



I think regex is not the best solution for me.





Edit, I couldn't respond to my own question, and comments don't let me format nicely.






Thanks, even though this worked in a regex checker, trying to use it in the context of the database, didn't work. I'm still working on that.



var str  = email.body_text;
var refStr = str.match((/number\:\s+(\d+)$/i)[1]);
externalReferenceNumberCreate(current.sys_id, 'Client reference number',refStr,'Ref number');



I know line 1 and 3 are correct, so perhaps I've messed the syntax for line 2? As



I understand that this is probably a product specific query, and perhaps more complicated than I thought.


Answer



Alex already gave you the answer: str.match(/number\:\s+(\d+)$/i)[1], which means the result at the index of 1. That index in the array is generated by the usage of the () in your regex. The first index (0) is the answer you've been getting.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...