My goal is to get the length till the nth occurrence of <br> tag in javascript so I am splitting them up.
I am trying regex
((.|\s)*?<br\s?/?>){2} //2 is the max number of lines(br tags) allowed.
While this is working fine in regexBuddy
but the string is splitted into multiple parts ignoring the <br\s?/?> part in browser.
you can view a fiddle here
What am I doing wrong
Wouldn't exec make more sense than split in this case?
var str=$('#op').html();
var match = /((.|\s)*?<br\s?\/?>){2}/i.exec(str);
if( match )
console.log(match[0].length);
The issue is that you are using the split() method, which will split the string up in to pieces based on the regular expression. This will not include your regular expression match. In your case the first section of the string matches your regular expression, so you would have an empty string at index 0 and everything after the regular expression match in index 1.
You should try to use the match() method instead, which will return an array of the pieces of the string that matched your regular expression.
var str=$('#op').html();
console.log(str.match(/(([\s\S])*?<br\s?\/?>){2}/i)[0].length);
See code.
Related
I have a string "QAWABAWONL", from which I want to remove ONLY a single occurrence of the character 'A'. It does not matter whether the first occurrence or the second occurrence gets removed, either is fine. I've found that using indexOf or includes removes all occurrences.
I'ts simple, there are many ways of doing this. I would use a regex:
myStr.replace(/A/i, "");
The i flag is for ignoring case. If you wanted to replace more than one occurrence you need the g flag but it's not your case.
Use String.replace and pass a substring for the first argument.
From the above link (emphasis mine):
substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
Usage:
let originalString = "QAWABAWONL";
let result = originalString.replace("A","");
console.log(result);
You can use regular expression in jscript, it's so easy:
example: alert("some text1, some tex2, some text3".replace('text1', ''));
Remove first occurrence of comma in a string
I hope it is useful !
I try to extract all text from document title before it gets to closest "|" or "-" or "/" . I assume i have to write something like this but im not good at regex.
var docTitle = document.title();
docTitle.match(regex);
Can someone help me with correct regex or suggest perhaps a better solution to achieve desired effect ?
Thank you !
Use var shortTitle = document.title.split(/[|\/-]/,1)[0];
The split function divides a string into an array based on a separator.
You can pass a Regular Expression object into the split function if the separator is a pattern and not constant.
The regular expression is [|/-] meaning any |, /, or -. The / needed to be escaped with a \ in JavaScript because / is also the character that delimits Regular Expression literals.
The first element of the split array ([0]) will be the document title before the first occurrence of any of those separator characters.
It will be the only element in the array, because we told the split function to stop after the first occurrence.
If the document title contains no matching characters to split on, the split function returns the whole string in the first array element, anyway.
I am trying to determine if a CSV string contains a specific number (also String), in this case the number 3. I have wrote some script to attempt this but the result always returns null. The regex works when using an online testing tool, however not when utilized via script. Can anyone determine what I'm missing?
Here is my code:
var csv = ["1,25,3","3", "1", "1,9,10", "2,4,5,6,7,11,33,3", "2,1,2,12,15,27"];
function contains(param){
var regex = /(,)?\D[3]\D(,)?/g;
return param.match(regex);
}
for(var i = 0; i < csv.length; i++){
console.log(contains(csv[i]));
}
Or if you prefer: JsFiddle
The problem is that your pattern requires a character (\D) before and after your 3. Since all 3s in your example are at the end of the string the second \D can never match. What you want is probably something like this:
var regex = /(?:^|\D)3(?!\d)/;
For the end of the string we use negative lookahead. That asserts that there is no digit. This is better than asserting that there is a non-digit character (because it works for the end of the string, too). Ideally, we would use the same for the beginning, but that is not supported by JavaScript. So we say, either we have the beginning of the string or a non-digit character. In fact (as Brad Koch pointed out), in this specific case, both conditions constitute a word boundary (a position between a character in [a-zA-Z0-9_] and one that is not or an end of the string). So you can simply use:
var regex = /\b3\b/;
However, if your input can include other characters than digits and commas (e.g. 1,text,2,a3b,somemoretext), none of these approaches are sufficient. Instead you need to check for commas explicitly:
var regex = /(?:^|,)3(?![^,])/;
Also, since you don't need the actual match, but only want to know whether there is a match, you can use test instead:
return regex.test(param);
This will give you a boolean instead of an array (which probably also makes is marginally more efficient).
I'm trying to write a regular expression in JS to recognize any digit up to seven times, followed by a "-" followed by 2 digits followed by "-" followed by a single digit. This is the simple regex I have:
/\d{1,7}-\d{2}-\d/g
This should match strings like:
123-12-7
1-12-7
1234567-12-7
but not 12345678-12-1
However, the above is returning true. The regex returns true when there is any number of digit in the first group.
Does the JavaScript Regex object not support {n,m}?
Here is an example of what I am talking about.
var pattern = new RegExp(/\d{1,7}-\d{2}-\d/);
alert(pattern.test("12345678-13-1"));
http://jsfiddle.net/XTRAc/1/ live example
It matches 2345678-13-1. You need to anchor it to the beginning and end of your string:
/^\d{1,7}-\d{2}-\d$/
Note though, that (as Rocket Hazmat pointed out) you do not need to use the RegExp constructor if you use a regex literal (something without string quotes).
JSFiddle
It does support the {min,max}-syntax, but .match and .test() try to find matching substrings. You will have to include start and end anchors. Also notice that you should either use the RegExp constructor to build a regex from a string or a regex literal, but not both (see MDN: creating regexes).
/^\d{1,7}-\d{2}-\d$/
new RegExp("^\\d{1,7}-\\d{2}-\\d$") // the worse choice
You are constructing your regex incorrectly. Try this (note the anchors, which ensure the string consists of nothing but your pattern):
var pattern= /^\d{1,7}-\d{2}-\d$/;
Otherwise subsets of the existing string will match your regex.
If you need to validate entire input string, use regex pattern
/^\d{1,7}-\d{2}-\d$/
If you need to validate entire line of input string, use regex pattern
/^\d{1,7}-\d{2}-\d$/mg
If you need to find matches within input string, use regex pattern
/(?:\D|^)(\d{1,7}-\d{2}-\d)(?!\d)/g
...and use $1 as a result.
It does support the {n,m} part, the problem here is that your example matches 2345678, so you would need a way of matching the character before the first set of digits
hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble.
I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.
var date = "02-25-2010";
var myregexp2 = new RegExp("-.");
dateArray = date.split(myregexp2);
What is the correct regex for this any and all help would be great.
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
or just (anything but numbers):
date.split(/\D/);
you could just use
date.split(/-/);
or
date.split('-');
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
Colon
Semicolon
New line
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
Then split it on anything but numbers:
date.split(/[^0-9]/);
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
try this instead
date.split(/\W+/)