Change only the number inside var? - javascript

If you have:
var something = $('.element').text();
// something = 'The tortoise ran 5 times faster than the fox.';
Is there a way I can edit it to change the "5" to a different number in a new var? So I get
newSomething = 'The tortoise ran 6 times faster than the fox.';
NOTE: the number from var something is dynamic and be anything from 0 -> 100's, I need to increment it by one and I need to increment it on the fly (I cannot assign the number to a var as it is coming from document load and is being assigned )

var something = $('.element').text();
var newSomething = something.replace(/\d+/, function(match) {
return (Number(match) + 1).toString();
});
Some info on what's happening: the code uses a more complex form of the str.replace function. The normal form just takes two strings, and replaces any occurrence of the first string with the second string.
str.replace can also take a regular expression to search for (in this case, \d+, which means "one or more digits"), along with a replacer function, as I've used here. I've used an anonymous function expression, which takes a single argument match. This function is called for every single match, so if your string has multiple matches, it'll be run multiple times.
In the function, the match (which is a string) is being converted to a number, incremented, and then converted back to a string. This is then returned as the result of the match replacer.

define a var ...
var num = 5;
var something = 'The tortoise ran ' + num + ' times faster than the fox.';
function whatever(){
num++;
something = 'The tortoise ran ' + num + ' times faster than the fox.';
}

How about in php wrapping a span around your number so you can access it easily with javascript:
HTML
<span class="element">The tortoise ran <span class="number">6</span> times faster than the fox.</span>
Then with javascript you can access the number easily:
Javascript
var number = Number($('.number').text());
$('.number').text(number + 1);
Demo

Related

How can I apply something like 'subtr' to cut a string with (...) in Meteor js?

In PHP we have functions to cut long texts, to make a kind of 'preview' by stoping the whole result with the subrt() function in order to put a limit to the string.
Is there any way of do the same but in JavaScript?
what I need is to show
blablablabla...
instead of blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla (the whole text) when showing results {{mytext}}
This is a relatively straight forward function to write in javascript.
Substring is a function in javascript with the signature str.substring(startIndex, [endIndex]). So if you wanted to take the first n characters from a string and then append an ellipses you could do the following
// verbose
function shorten(str, n) {
var chopped = str.substr(0, n);
var formatted = chopped + '...';
return formatted;
}
// one liner
function shorten(str, n) {
return str.substr(0, n) + '...';
}
// shorten('foobarbatbaz', 3) -> 'foo...'
I don't know about meteor, but javscript itself has a substr function for strings, <string>.substr(<length>) for instance "asdf123123123123123".substr(4) gives you "asdf"
EDIT: it gives you "123123123123123", I was thinking of substr(0,4)

Split a text and put some text between them

i have a Javascript code from an extension im creating and i need to split the word im selecting in like, half for each part...
for example this is my code that i use for every page i need
function child1_7Search(info,tab) {
chrome.tabs.create({
url: "www.blablabla.com/" + info.selectionText,
});
}
but i have to split the selected code in 2. For example, my selected code is 1854BIGGER000208, where the first four letters need to be split in half and put somewhere in the URL and the other twelve letters needs to be put in other place, but in the URL.
the page needs to look something like this
https://www.urbano.com.ar/urbano3/wbs/cespecifica/?shi_codigo=001854&cli_codigo=BIGGER000208
where in shi_codigo adds two zeros and put the first half, and in cli_codigo puts the rest of the code.
The selected code its always the same length!
you can try to concatenate parts like this..
// this is your original text / code that you get
var text = "1854BIGGER000208"
// here we `slice` or take first 4 chars from it
var pret = text.slice(0,4);
// here we are taking other half of the text
var post = text.slice(4);
// and here we just concatenate them into final url part
var final = "shi_codigo" + "00" + pret + "&cli_codigo=" + post
console.log( final );
I guess that you will want to concatenate the first part of the url also and for that you can also prepend it with + sign as we did with all parts of the code above..
Here's a simple solution using .substring() method:
var code = "1854BIGGER000208";
var shi = "00" + code.substring(0, 4);
var cli = code.substring(4);
var url = "https://www.urbano.com.ar/urbano3/wbs/cespecifica/?shi_codigo=" + shi + "&cli_codigo=" + cli;
console.log(url);
Note:
code.substring(0, 4) will extract the first four digits from the selection, returns 1854.
And code.substring(4) will extract the remaining characters in the selection and returns BIGGER000208.
Note the use of "" in "00" the two zeros are wrapped in a string
so they can be concatenated with the shi code, otherwise 00+1854 will
be evaluated as 1854.
Here are a number of string functions you can use in JavaScript.
https://www.w3schools.com/jsref/jsref_obj_string.asp
In particular, you may want to use the slice function. Syntax is as follows :
var l = info.selectionText.length() - 1;
var num = info.selectionText.slice(0,3);
var end = info.selectionText.slice(4, l);
Here, the properties being passed into the slice function are the start and stop points of where you would like to slice the string. As usual, the index starts at 0.
Solution using ES6 Sintax
let yourString = "yourstringthatneedstobesliced";
let initial = yourString.slice(0,4);
let post = yourString.slice(4);
let char = `shi_codigo=00${initial}&cli_codigo=${post}`;

Regext to match any substring longer than 2 characters

regex-pattern-to-match-any-substring-matching exact characters longer-than-two-characters-from-a-provided input,where ever exact string matches
Only pot or potato should be highlighted, instead of ota or ot, when user type pota and click search button.
Please find code below where matched string is highlighted.
// Core function
function buildRegexFor(find) {
var regexStr = find.substr(0,3);
for (var i = 1; i < find.length - 2; i++) {
regexStr = '(' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
}
return regexStr;
}
// Handle button click event
document.querySelector('button').onclick = function () {
// (1) read input
var find = document.querySelector('input').value;
var str = document.querySelector('textarea').value;
// (2) build regular expression using above function
var regexStr = buildRegexFor(find);
// (3) apply regular expression to text and highlight all found instances
str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>");
// (4) output
document.querySelector('span').textContent = regexStr;
document.querySelector('div').innerHTML = str;
};
consider "meter & parameter" as one string, if type meter in input box and click search button. meter should be highlighted as well as meter in parameter should highlight.Thanks in advance
Your for loop is set to go from i = 1, while i is less than find.length-2. find.length is 4. 4-2 is 2. So your for loop is set to go from i = 1 while i is less than 2. In other words, it's operating exactly once. I have no idea what you thought that for loop was going to do, but I'm betting that isn't it.
Prior to the for loop, regextr is set equal to the string pot (the first three characters of the find string. The first (and only) time through the for loop, it is set to a new value: the left paren, the existing value (pot), the fourth character of find (a), the question mark, the vertical bar, and three characters from find starting with the second. Put those together, and your regextr comes out to:
(pota?|ota)
That RegEx says to find either the string "pota" (with the a being optional, so "pot" also works) or the string "ota". So any instances of pota, pot, or ota will be found and highlighted.
If you just wanted "pota?", just eliminate the right half of that line inside the for loop. Better yet, replace the entire subroutine with just a line that appends the ? character to the find string.

Javascript: Trouble Converting String to Number

Given the circumstances I have to use a node list to get at elements that I need to work with. I am able to use .textContent (or .nodeValue) to return a string that I need, but I am having trouble finding a way to get that string into any type of number. I need to have it in number form so I can perform calculations with it. I have tried Number(), parseInt(), etc. All return NaN. I am pretty new to JS so hopefully this is an easy issue to solve.
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(siteActual); // test variable to convert string to number
console.log(asd); // returns NaN
EDIT: I checked .length as one of you suggested and it was 2, so those saying it may be an invisible character are probably right. I am trying to make changes to a SharePoint page, that is why I am not familiar with what the markup is. Any suggestions on how to remove all but the number would be helpful.
Your code should work as-is if the content is really just 1 (as should parseInt). So there must be something other than valid numbers in your content.
Sometimes there can be content that you can't see, e.g. in the example below the second td contains an invisible "zero-width space" character.
var tdNodeListActual = document.querySelectorAll("td");
var good = tdNodeListActual[0].textContent;
var bad = tdNodeListActual[1].textContent;
alert(good + "==" + Number(good) + ", but " + bad + "==" + Number(bad))
<table><tr>
<td>1</td>
<td>​2</td>
</tr></table>
You can remove all non-digit characters (except . and ,) using a regex, e.g.:
siteActual = siteActual.replace(/[^\d.,]/g, '');
Using parseInt(...)
Sample:
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(parseInt(siteActual)); // test variable to convert string to number
console.log(asd); // should return 1

regex - get numbers after certain character string

I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the = sign in the string ?order_num=
So the whole string would be
"aijfoi aodsifj adofija afdoiajd?order_num=3216545"
I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the ?order_num=203823 into its own variable.
I'll post some attempts of my own, but I foresee failure and confusion.
var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var m = s.match(/([^\?]*)\?order_num=(\d*)/);
var num = m[2], rest = m[1];
But remember that regular expressions are slow. Use indexOf and substring/slice when you can. For example:
var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);
I see no need for regex for this:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?");
n will then be an array, where index 0 is before the ? and index 1 is after.
Another example:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?order_num=");
Will give you the result:
n[0] = aijfoi aodsifj adofija afdoiajd and
n[1] = 3216545
You can substring from the first instance of ? onward, and then regex to get rid of most of the complexities in the expression, and improve performance (which is probably negligible anyway and not something to worry about unless you are doing this over thousands of iterations). in addition, this will match order_num= at any point within the querystring, not necessarily just at the very end of the querystring.
var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
alert(match[1]);
}

Categories

Resources