logoologist
logoologist

Reputation: 205

String prototype syntax for matching specific pattern in string

Let's say I want to get the string position of the first character of 11-22 (dd-dd).
The syntax of prototypes isn't clear to me yet, but I believe I'm close.

For some reason, the code works now if I have 11 - 22 but without those spaces it doesn't work.
Also, I want to exclude any matches that have more than two numbers on either side of the -.
I don't want to match 1111-2222, only 11-22.

function myFunction() {
var str = 'For more information, 11-22 1111-2222';
var re = /\d+\d+\ +[-]+ \d+\d/i;
document.getElementById("result").innerHTML=(str.search(re));
}
<body onload="myFunction()">

<p>result: <span id="result"></span></p>

Upvotes: 0

Views: 20

Answers (3)

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21756

If you want to just check position of specific string then you can do it with str.indexOf(your pattern) as well.

Check below code:

function myFunction() {
var str = 'For more information, 11-22 1111-2222';
var re = "11-22";
document.getElementById("result").innerHTML=(str.indexOf(re));
}
<body onload="myFunction()">

<p>result: <span id="result"></span></p>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

Since it looks like the spaces are optional, you should quantify them with * (zero or more occurences). If you want exactly two digits, then use \d\d rather than quantify both digits with +, which doesn't make much sense when they're right next to each other:

function myFunction(str) {
  console.log(str.search(/\b\d\d *- *\d\d/));
}
myFunction('For more information, 11-22 1111-2222');
myFunction('For more information, 11 - 22 1111-2222');
myFunction('foobar, 11 - 22 1111-2222');
myFunction('1111-2222 11 - 22');

Upvotes: 1

VorpalSword
VorpalSword

Reputation: 1293

Try https://regexr.com which has an interactive play pen where you can iterate your way to getting the regex you need.

(\D1{2}-2{2}\D)

is what I came up with which is close to, but not quite what you want.

Upvotes: 1

Related Questions