quantity of white spaces left of a string jQuery - javascript

I need to count the white spaces left of a string with jQuery.
For example:
String: " Hello how are you? " will have 4 white spaces at its left!
How can i get that with jQuery?
thanks.

Using regexp in plain old JavaScript:
var spacesOnLeft = myStr.match(/^ */)[0].length
No loops involved. :)

This is something that's doable with plain old javascript.
function countLeftBlanks(arg) {
var i = 0;
while (i < arg.length && arg[i] === ' ') {
i++;
}
return i;
}

If we're using RegExp, the below might be a better cross-environment solution:
var spacesOnLeft = ( myStr.match(/^ */) || [[]] )[0].length;
The above stops a TypeError from being thrown in certain environments when the result of match is null. In the official ECMAScript Language Specification, the match method states that:
If n = 0, then return null.
Despite this, most modern browsers seem to return an array with an empty string in it. In some environments, however, the ECMAScript definition is honoured, and a TypeError will be thrown if attempting to access matched[0]. The NodeJS environment is a good example of this.

Related

How to access the first two digits of a number

I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!

How to use lastIndexOf() function with symbols

Just started using indexOf() and lastIndexOf() functions and I know why they are used, however, the result doesn't make me feel happy :)
let str = $('#info').html();
// WORKS
//alert(str.lastIndexOf('√'));
// DOESN'T WORK
alert(str.lastIndexOf('√'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">√</div>
The problem is I get the alert result as "-1", which means the √ couldn't be found in the str variable. Using simple symbol √ it works, however, I'm not sure if it's a good practice using this symbol here.
In my opinion, another approach about this problem would be encoding √ symbol in the HTML to √, so using "Inspect element" feature you would see √.
What do you think?
There is no direct way to achieve this. But if you still want to do this way then you simply need to create a HEX value of the ASCII value:
let str = ascii_to_hexa($('#info').html());
str = '&#x0'+str.toUpperCase()+';';
alert(str.lastIndexOf('√'));
function ascii_to_hexa(str)
{
var arr1 = [];
for (var n = 0, l = str.length; n < l; n ++){
var hex = Number(str.charCodeAt(n)).toString(16);
arr1.push(hex);
}
return arr1.join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">√</div>
When the browser reads and parses your HTML, it builds up a DOM, without retaining the exact HTML you provided. Later, if you ask for HTML, it builds a new HTML string using its own rules for doing that.
That's why str.lastIndexOf('√') doesn't work: The browser isn't under any obligation to give you back the character in the same form you used when you supplied it. It could give it back as just a character (√) or a named character reference (√ in this case) or a decimal numeric character reference (√), rather than the hex numeric character reference you're looking for.
You'll have to test on your target browsers to see what they give you, and then look for that. I suspect most if not all will return the actual character, and so your str.lastIndexOf('√') (or str.lastIndexOf('\u221A')) will be the way to go.
<div>√</div>

How to create a string with n characters? How to create a string with specific length? [duplicate]

This question already has answers here:
Repeat String - Javascript [duplicate]
(30 answers)
Closed 7 years ago.
I'm writing JavaScript unit tests and I need to create a string of length 65536.
What's the best way to do this in JavaScript?
Currently I'm using:
var myString = '';
for (var i = 0; i <= 65535; ++i) {
myString += 'x';
}
This is a forward-looking answer, and won't work in current implementations.
ECMAScript 6 is currently defining a String.prototype.repeat method. This will allow you to do:
var result = "x".repeat(65535);
Again, this is a future addition. Currently ECMAScript 6 (Harmony) is being drafted, and this could technically be removed, though it doesn't seem likely.
Current draft:
15.5.4.21 String.prototype.repeat (count)
The following steps are taken:
Let O be CheckObjectCoercible(this value).
Let S be ToString(O).
ReturnIfAbrupt(S).
Let n be the result of calling ToInteger(count).
ReturnIfAbrupt(n).
If n < 0, then throw a RangeError exception.
If n is +Infinity, then throw a RangeError exception.
Let T be a String value that is made from n copies of S appended together. If n is 0, T is the empty String.
Return T.
NOTE 1 This method creates a String consisting of the string elements of this object (converted to String) repeated
count time.
NOTE 2 The repeat function is intentionally generic; it does not require that its this value be a String object.Therefore, it can be transferred to other kinds of objects for use as a method.
How about
Array(65537).join('x')
Note, that it's 65537, not 65536, because you put characters inbetween.
Array.prototype.join doesn't have to be called on an Array, just an Object with a length property (tested in Google Chrome, FireFox, IE10)
function makeStr(len, char) {
return Array.prototype.join.call({length: (len || -1) + 1}, char || 'x');
}
makeStr(5); // "xxxxx"
This lets you benefit from native function making the string, without the overhead of a huge array.
Out of interest, I created a quick benchmark test on jsperf.com:
http://jsperf.com/mkstring
Contestants are
Array(x).join()
Array.prototype.join posted by Paul S.
strRepeat from underscore.string
function strRepeat(str, qty) {
if (qty < 1) return '';
var result = '';
while (qty > 0) {
if (qty & 1) result += str;
qty >>= 1, str += str;
}
return result;
}
strRepeat('*', 20000);
EMCAScript 6 String.repeat mentioned by Crayz Train
For Firefox 34 (which already supports the ECMAScript6 String.repeat), the native repeat is the fastest, followed by strRepeat.
Interestingly with Chrom(e|ium) 39 the strRepeat function is even faster compared to the native String.repeat function of Firefox in my test runs.
For all tested browsers, the function proposed by Paul S. using the native Array.join method is slower than the strRepeat function of the underscore.string library. So, don't use it if you're looking for a fast method.
You could create an array of length whatver you want and then use the join() method on the array which will make it into a string. Array(number).join(char) this creates an array on size number -1. Also note that you do not want to use your method because concatenating strings is very expensive(O(n) every concat). I am not sure if javascript has a StringBuilder like java

CodeMirror - Using RegEx with overlay

I can't seem to find an example of anyone using RegEx matches to create an overlay in CodeMirror. The Moustaches example matching one thing at a time seems simple enough, but in the API, it says that the RegEx match returns the array of matches and I can't figure out what to do with it in the context of the structure in the moustaches example.
I have a regular expression which finds all the elements I need to highlight: I've tested it and it works.
Should I be loading up the array outside of the token function and then matching each one? Or is there a way to work with the array?
The other issue is that I want to apply different styling depending on the (biz|cms) option in the regex - one for 'biz' and another for 'cms'. There will be others but I'm trying to keep it simple.
This is as far as I have got. The comments show my confusion.
CodeMirror.defineMode("tbs", function(config, parserConfig) {
var tbsOverlay = {
token: function(stream, state) {
tbsArray = match("^<(biz|cms).([a-zA-Z0-9.]*)(\s)?(\/)?>");
if (tbsArray != null) {
for (i = 0; i < tbsArray.length; i++) {
var result = tbsArray[i];
//Do I need to stream.match each element now to get hold of each bit of text?
//Or is there some way to identify and tag all the matches?
}
}
//Obviously this bit won't work either now - even with regex
while (stream.next() != null && !stream.match("<biz.", false)) {}
return null;
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), tbsOverlay);
});
It returns the array as produced by RegExp.exec or String.prototype.match (see for example https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match), so you probably don't want to iterate through it, but rather pick out specific elements the correspond to groups in your regexp (if (result[1] == "biz") ...)
Look at implementation of Code Mirror method match() and you'll see, that it processes method parameter for two types: string and RegExp.
Your constant in
stream.match("<biz.")
is of string type.
Define it in RegExp type:
tbsArray = /<biz./g
Thus, your stream will be matched with RegExp.

Convert string into storable variable names and values (as strings, and objects)

2015 Edit Don't do this. Be a good person and Just Use JSON.parse() :)
I am trying to take a string which contains variables and values in a javascript-like syntax, and store them in a global object (gv). My issue is just with the parsing of the string.
String (everything inside the <div>):
<div id="gv">
variableName = "variableValue,NoSpacesThough";
portal = "TheCakeIsALie";
</div>
Script (parses string above, places values into global object):
var s = (document.getElementById("gv").innerHTML).split(';');
for (var i = 0; i < s.length; i++) {
if (s[i] !== "\n" || "") {
s[i] = s[i].replace(/^\s*/gm, "");
var varName = s[i].substr(0, s[i].indexOf('=') - 1),
varValue = (s[i].substr((s[i].indexOf('"') + 1), s[i].length)).replace('"', "");
gv[varName] = varValue;
}
}
Result:
console.log(gv.variableName); //returns: variableValue,NoSpacesThough
console.log(gv.portal); //returns: TheCakeIsALie
Q: How can I modify this script to correctly store these variables:
exampleVariable = { name: "string with spaces", cake:lie };
variableName = "variableValue,NoSpacesThough";
portal = "The Cake Is A Lie";
The directly above has an object containing: A string with spaces (and "), a reference
Thanks.
Four options / thoughts / suggestions:
1. Use JSON
If you're in control of the source format, I'd recommend using JSON rather than rolling your own. Details on that page. JSON is now part of the ECMAScript (JavaScript) standard with standard methods for creating JSON strings from object graphs and vice-versa. With your example:
exampleVariable = { name: "string with spaces", cake:lie };
variableName = "variableValue,NoSpacesThough";
portal = "The Cake Is A Lie";
here's what the JSON equivalent would look like:
{
"exampleVariable": { name: "string with spaces", cake:lie },
"variableName": "variableValue,NoSpacesThough",
"portal": "The Cake Is A Lie"
}
As you can see, the only differences are:
You wrap the entire thing in curly braces ({}).
You put the "variable" names (property names) in double quotes.
You use a colon rather than an equal sign after the property name.
You use a comma rather than a semicolon to separate properties (just as in the object literal you have on your exampleVariable line).
You ensure that any string values use double, rather than single, quotes (JavaScript allows either; JSON is more restrictive). Your example uses double quotes, but I mention it just in case...
2. Pre-process it into JSON with regular expressions
If you're not in control of the source format, but it's exactly as you've shown, you could reformat it as JSON fairly easily via regular expressions, and then deserialize it with the JSON stuff. But if the format is more complicated than you've quoted, that starts getting hairy very quickly.
Here's an example (live copy) of transforming what you've quoted to JSON:
function transformToJSON(str) {
var rexSplit = /\r?\n/g,
rexTransform = /^\s*([a-zA-Z0-9_]+)\s*=\s*(.+);\s*$/g,
rexAllWhite = /\s+/g,
lines,
index,
line;
lines = str.split(rexSplit);
index = 0;
while (index < lines.length) {
line = lines[index];
if (line.replace(rexAllWhite, '').length === 0) {
// Blank line, remove it
lines.splice(index, 1);
}
else {
// Transform it
lines[index] = line.replace(rexTransform, '"$1": $2');
++index;
}
}
result = "{\n" + lines.join(",\n") + "\n}";
return result;
}
...but beware as, again, that relies on the format being exactly as you showed, and in particular it relies on each value being on a single line and any string values being in double quotes (a requirement of JSON). You'll probably need to handle complexities the above doesn't handle, but you can't do it with things like your first line var s = (document.getElementById("gv").innerHTML).split(';');, which will break lines on ; regardless of whether the ; is within quotes...
3. Actually parse it by modifying a JSON parser to support your format
If you can't change the format, and it's less precise than the examples you've quoted, you'll have to get into actual parsing; there are no shortcuts (well, no reliable ones). Actually parsing JavaScript literals (I'm assuming there are not expressions in your data, other than the assignment expression of course) isn't that bad. You could probably take a JSON parser and modify it to your needs, since it will already have nearly all the logic for literals. There are two on Crockford's github page (Crockford being the inventer of JSON), one using recursive descent and another using a state machine. Take your choice and start hacking.
4. The evil eval
I suppose I should mention eval here, although I don't recommend you use it. eval runs arbitrary JavaScript code from a string. But because it runs any code you give it, it's not a good choice for deserializing things like this, and any free variables (like the ones you've quoted) would end up being globals. Really very ugly, I mostly mention it in order to say: Don't use it. :-)

Categories

Resources