Regular Expression on Javascript - javascript

I have snippet javascript (web) but since i try to use RegExpression it should work almost the same.
I have a string with some coordinates in it seperated by a space charakter (last coordinate has no space after it).
var coords = "0:0 0:0:0 1:0:1 0:0:0:1 0:0:1 0:0:2";
var part = "0:0";
I want to have all the coordinates beginning with the value of part ("0:0") plus ":" and the next coordinate number. If a coordinate matches but has more than one additional "coordinate-dimensions" it shouldn't show...
For example it should show 0:0:0, 0:0:1 and 0:0:2 but NOT 0:0 (because to less dimension), 0:0:0:1 (because if the additional dimension)
What I tryed is something like:
var reg = new RegExp("(^|\\s)(0:0:\\d\\s)", "g");
alert(coords .match(reg));
But it seems not to work propperly.
Anyone has an idea?!
Kind regards!

You can use this regex:
"(?:^|\\s)(0:0:\\d)(?=\\s|$)"

Related

How to make abbreviation of underscore or hyphen separated words using regex in JavaScript?

I need to make abbreviation of hyphen or underscore separated words, For instance:
hyphen-separated-words
underscore_separated_words
I use the code below for hyphen-separated-words, and it works fine.
var hyphenSeparatedWords = "hyphen-separated-words";
var abbr = hyphenSeparatedWords.match(/\b([a-z])/g).join('');
console.log(abbr) // hsw
For underscore_separated_words, I use the code below. It works fine, but there are a lot of repetitions.
var underscoreSeparatedWords = "underscore_separated_words";
var abbr = underscoreSeparatedWords.replace(/_/g, '-').match(/\b([a-z])/g).join('');
console.log(abbr) // usw
How to make an abbreviation of underscore_separated_words in the same way as the hyphen-separated-words without using replace?
How can I combine these two steps?
Update
I have a d3 bar chart that we use internally. My font is large. And some of the xAxis labels are too long and overlaps other elements.I had two choices to fix the issue.
Wrap labels like this in bl.ocks.org
Make an abbreviation of them. When you hover on a bar or its label, display the complete name.
I opted to go for the second. Because the first one still occupies a lot of place.
Why don't you try with a regex in split that will split with either - or _ and join them at the end after getting the first character.
function abbr(words){
return words.split(/-|_/).map(item=>item.charAt(0)).join('');
}
var words = 'hyphen-separated-words';
var res = abbr(words);
console.log(res);
words = 'underscore_separated_words';
res = abbr(words);
console.log(res);
I do not know why do not want to use replace but you can use a replace one liner, and use a replacer function:
"underscore_separated_words".replace(/[A-Z]+?(?:[_-]|\b)/gi,function(m,o,s){return m.slice(0,1)}); //usw
I think the above is way more concise and elegant
An alternate solution if you'd like to work on whole sentences:
var str = 'Leave normal words and only abreviate underscore_separated_words.';
console.log(str.replace(/(?:_|(?=[a-z]*_))([a-z])[a-z]*/gi, '$1'));
Here at regex101.

I need some help for a specific regex in javascript

I try to set a correct regex in my javascript code, but I'm a bit confused with this. My goal is to find any occurence of "rotate" in a string. This should be simple, but in fact I'm lost as my "rotate" can have multiple endings! Here are some examples of what I want to find with the regex:
rotate5
rotate180
rotate-1
rotate-270
The "rotate" word can be at the begining of my string or at the end, or even in the middle separated by spaces from other words. The regex will be used in a search-and-replace function.
Can someone help me please?
EDIT: What I tried so far (probably missing some of them):
/\wrotate.*/
/rotate.\w*/
/rotate.\d/
/\Srotate*/
I'm not fully understanding the regex mechanic yet.
Try this regex as a start. It will return all occurrences of a "rotate" string where a number (positive or negative) follows the "rotate".
/(rotate)([-]?[0-9]*)/g
Here is sample code
var aString = ["rotate5","rotate180","rotate-1","some text rotate-270 rotate-1 more text rotate180"];
for (var x = 0; x < 4; x++){
var match;
var regex = /(rotate)([-]?[0-9]*)/g;
while (match = regex.exec(aString[x])){
console.log(match);
}
}
In this example,
match[0] gives the whole match (e.g. rotate5)
match[1] gives the text "rotate"
match[2] gives the numerical text immediately after the word "rotate"
If there are multiple rotate stings in the string, this will return them all
If you just need to know if the 'word' is in the string so /rotate/ simply will be OK.
But if you want some matching about what coming before or after the #mseifert will be good
If you just want to replace the word rotate by another one
you can just use the string method String.replace use it like var str = "i am rotating with rotate-90"; str.repalace('rotate','turning')'
WHy your regex doesnt work ?
/\wrotate.*/
means that the string must start with a caracter [a-zA-Z0-9_] followed by rotate and another optional character
/rotate.\w*/
meanse rotate must be followed by a character and others n optional character
...............
Using your description:
The "rotate" word can be at the beginning of my string or at the end, or even in the middle separated by spaces from other words. The regex will be used in a search-and-replace function.
This regex should do the work:
const regex = /(^rotate|rotate$|\ {1}rotate\ {1})/gm;
You can learn more about regular expressions with these sites:
http://www.regular-expressions.info
regex101.com and btw here is an example using your requirements.

Regular Expression (string compare)

I have written this in javascript (web) but since i try to use RegExpression it should work almost the same.
I have a string with some coordinates in it seperated by a space charakter.
var coords = "0:0 0:0:0 1:0:1 0:0:0:1";
var part = "0:0";
I want to have all the coordinates beginning with the value of part ("0:0");
What I tryed is something like:
var reg = new RegExp(part+"*");
alert(coords .match(reg));
But it seems not to work propperly.
It should match "0:0" and "0:0:0" and "0:0:0:1" but NOT "1:0:1" (edit)
Anyone has an idea?!
Kind regards!
You should use this regex:
var reg = new RegExp("(^|\\s)(" + part + "\\S*)", "g");
that is to match all non-space characters after 0:0 and stop when it hits a space or line end.

JavaScript - How to get at specific value in a string?

I have a string from which I am trying to get a specif value. The value is buried in the middle of the string. For example, the string looks like this:
Content1Save
The value I want to extract is "1";
Currently, I use the built-in substring function to get to remove the left part of the string, like this:
MyString = "Content1Save";
Position = MyString;
Position = Position.substring(7);
alert(Position); // alerts "1Save"
I need to get rid of the "Save" part and be left with the 1;
How do I do that?
+++++++++++++++++++++++++++++++++++++++++
ANSWER
Position = Position.substr(7, 1);
QUESTION
What's the difference between these two?
Position = Position.substr(7, 1);
Position = Position.substring(7, 1);
You can use the substr[MDN] method. The following example gets the 1 character long substring starting at index 7.
Position = Position.substr(7, 1);
Or, you can use a regex.
Position = /\d+/.exec(Position)[0];
I would suggest looking into regex, and groups.
Regex is built essentially exactly for this purpose and is built in to javascript.
Regex for something like Content1Save would look like this:
rg = /^[A-Za-z]*([0-9]+)[A-Za-z]*$/
Then you can extract the group using:
match = rg.exec('Content1Save');
alert(match[1]);
More on regex can be found here: http://en.wikipedia.org/wiki/Regular_expression
It highly depends on the rules you have for that middle part. If it's just a character, you can use Position = Position.substring(0, 1). If you're trying to get the number, as long as you have removed the letters before it, you can use parseInt.
alert(parseInt("123abc")); //123
alert(parseInt("foo123bar")); //NaN
If you're actually trying to search, you'll more often than not need to use something called Regular Expressions. They're the best search syntax JavaScript avails.
var matches = Position.match(/\d+/)
alert(matches[0])
Otherwise you can use a series of substr's, but that implies you know what is in the string to begin with:
MyString.substr(MyString.indexOf(1), 1);
But that is a tad annoying.

Count regular expression matches in jQuery

I need to count a group of regular expressions in a dynamically loaded <div> that I've loaded using the load() function. I also need to resize this <div> to the longest line of characters in it. Is there a way to achieve this? I've tried searching around and can't find anything, not even on SO. I should mention that the expression I am testing for is:
Sat Mar 12 12:45:38 PST 2011
Using this regex:
if ($('#result').text().match(/[A-Za-z]{3}\s[A-Za-z]{3}\s[0-9]{1,2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s[0-9]{4}/))
var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi; //noticed the g. g will enable match of all occurance, and without it it'll only match the first occurance
console.log(str.match(patt1).length); //4 matched
JavaScript match regex function returns an array so you can basically do a length on that array and get the size of the matched elements. Make sure you are using the g in RegEx to search all occurance
Based on your RegEx you can do the following:
$('#result').text().match(/[A-Za-z]{3}\s[A-Za-z]{3}\s[0-9]{1,2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s[0-9]{4}/g).length //this should give you the total count of occurance
kjy112 gave you your answer. Like that answer clarified, this isn't really jQuery, but Javascript RegEx's (so maybe that was throwing off your search).
If that regex turns out to be slow-- which it might if you return many dates-- you can just count some nique component, such as just the years:
$('#result').text().match(/\d{4}/).length
Malfy,
3 ways to get the width of a string come to mind. I'll go over those first, then how to get the length of the longest. It looks like others have addressed the regex.
1) (fastest)
If only the text itself needs to be a certain width, not the div, then you can use white-space:nowrap to ensure the text remains the full width.
$('div.someClass').css('whiteSpace','nowrap');
2) (slowest)
If you need the pixel width of a string to set another div's width, one way to do that is to create an element containing that string and use the css property above. Example:
var yourString = 'your string';
// create a div containing your string
var $tempDiv = jQuery('<div style="visibility:hidden;position:absolute;white-space:nowrap">'+jQuery.trim(yourString)+'</div>').appendTo('body');
$newDiv = <your new div, however you're creating it>;
// set the width of the new div to the width of the temp div
$newDiv.width($tempDiv.width());
// and clean up;
$tempDiv.remove();
//repeat as necessary
3) (quite fast too)
Alternately, if you're sure you'll be using a monospace font (courier, consolas, etc). There's a much faster way. Save the width of a single character and multiplying it by the length of each new text string. That way you aren't writing a new element each time. For example:
var $tempDiv = $('<div style="visibility:hidden;margin:0;padding:0;border:0;">z</div>').appendTo('body');
//(any character will work. z is just for example);
var reusableCharacterWidth=$tempDiv.width();
$tempDiv.remove();
var firstString = your string';
// set the width of your first div
$newDiv.width(reusableCharacterWidth*firstString.length);
var nextString = 'your next string';
// set the width of your next div
$nextNewDiv.width(reusableCharacterWidth*nextString.length);
(note: you may want to use $.trim() on the strings just in case)
To get the longest string:
var longestLineLength,
yourText= 'your text here';
function getLongestLineLength(lines){
var oneLineLength,
longest=0,
linesArray = lines.split('\n');
for(var i=0,len=linesArray.length;i<len;i++){
oneLineLength=linesArray[i].length;
longest=oneLineLength>longest?oneLineLength:longest;
}
return longest;
}
longestLineLength = getLongestLineLength(yourText);
Cheers!
Adam

Categories