Split a text and put some text between them - javascript

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}`;

Related

RegEx for matching the first instance of a URL

Say I have the HTML in a string variable htmlString and I want to find the first instance of an mp3 link in the html, and store that link in a variable.
<html>
...
src="https://example.com/mp3s/2342344?id=24362456"
...
</html>
The link https://example.com/mp3s/2342344?id=24362456 will be extracted.
Note there are lots of other urls in the html, but I just want the one in this format.
How do I get this?
While it is not usually recommended to parse HTMLs using regular expressions, this expression might help you to design an expression, if you wish/have to get the first mp3 URL.
^(src=\x22(https:\/\/[a-z]+.com\/mp3s\/[0-9]+\?id=[0-9]+)\x22)[\s\S]*
I have added several boundaries to it, just to be safe, which you can simply remove it from or simplify it in the second capturing group where your desired URL is:
(https:\/\/[a-z]+.com\/mp3s\/[0-9]+\?id=[0-9]+)
The key is that to add a [\s\S]* such that it would pass everything else after capturing the first URL.
Graph
This graph shows how it would work:
JavaScript Demo with 10 million times performance benchmark
repeat = 10000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = 'src=\"https://example.com/mp3s/2342344?id=24362456\" src=\"https://example.com/mp3s/08103480132984?id=0a0f8ad0f8\" src=\"https://example.com/mp3s/2342344?id=24362456\" href=\"https://example.com/mp3s/2342344?id=91847890\" src=\"https://example.com/mp3s/2342344?id0980184\"';
var regex = /^(src=\x22(https:\/\/[a-z]+.com\/mp3s\/[0-9]+\?id=[0-9]+)\x22)[\s\S]*/g;
var match = string.replace(regex, "$2");
}
end = Date.now() - start;
console.log(match + " is a match 💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

JS Elegent way to split a relative URLmultiple times to get only a part of the URL?

So I got this function where I retrieve a URL from SP2010. Which gives me a relative URL that does me no good.
e.g.
8;#reports/125/ReportList/closedTasks.rdl
I split this multiple times to retrieve the part I need.
For one var I need the reports/125/ReportList/closedTasks.rdl
So the part after the #. And only split method required to do so.
But for an other var I only need the file name without the extension.
So only closedTasks.
Because of this I need the do multiple split method like below.
Is there a more elegant way to do so?
var relName = ($(this).attr("ows_FileRef")).split("#")[1];
var relNameSub = relName.split("/")[3];
var name = relNameSub.split(".")[0];
You can use .slice() and .lastIndexOf()
var url = "8;#reports/125/ReportList/closedTasks.rdl";
var hash = url.slice(3); // slice the first 3 characters
var fileName = url.slice(url.lastIndexOf("/") + 1, url.lastIndexOf(".")); // slice following last "/" ending at `"."`
console.log(hash, fileName);
You can use the following regex, in order to match two capturing groups as you've defined.
Within context this would look like:
var match = (/^.*#(.*\/([.\w]+)$)/g).exec("8;#reports/125/ReportList/closedTasks.rdl");
// match[1] = "reports/125/ReportList/closedTasks.rdl"
// match[2] = "closedTasks.rdl"
Explanation:
The first capturing group contains everything after a #
The second capturing group (within the first one) contains all the alpha-numeric\dot characters after the last /.

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.

Change only the number inside var?

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

Regular expression in Javascript (without jQuery)?

I am new to Javascript and recently I wanted to use regular expression in order to get a number from url and store it into a var as string and another var as digit. For example I want to get the number 55 from the below webpage (which is not an accrual page) and I want to store it in a var.
I tried this but it is not working
https://www.google.com/55.html
url.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
Please I need help but not with jQuery because it does not make a lot of sense to me.
var numPortion = url.match(/(\d+)\.html/)[1]
(Assumes a match; if it might not match, check the results before applying the array subscript.)
Try this
var a="https://www.google.com/55.html";
var match = a.match(/(\d+)(\.html)/);
match is an array,
match[0] contains the matched expression from your script,
match[1] is the number (the 1st parenthesis),
and so on
var url = 'http://www.google.com/55.html';
var yournumber = /(\d+)(\.html)$/.exec(url);
yournumber = yournumber && yournumber[1]; // <-- shortcut for using if else

Categories

Resources