Program a JavaScript loop to take out characters - javascript

Suppose I've this code:
XBGa_AHjhdjsDjk_sad/safasdf_Sdfsdfasfdsa
I want to take XBGa_AHjhdjsDjk_sad out of this. I want to run a loop in JavaScript which appends each character to a variable and if the character is / the loop is terminated.
How do I do that?

var str = 'XBGa_AHjhdjsDjk_sad/safasdf_Sdfsdfasfdsa';
var spl = str.split('/');
var result = spl[0]; // This will be equal to XBGa_AHjhdjsDjk_sad
I am not sure if you mean that you want the first or second part of the string, but you get the idea. spl becomes an array after executing the split method.

I think your solution can be done much simpler than looping through each character
var old_val = 'XBGa_AHjhdjsDjk_sad/safasdf_Sdfsdfasfdsa';
var new_val = old_val.substring(old_val.indexOf('/')+1); //this will find the "/" and take the string after it

Related

Convert char to String in Javascript

Read it, Before it gets marked as duplicate
Sorry! I couldn't come up with a better description of the question
Anyways, I was making a simple program which reverses the given word (e.g 'word' to 'drow'). I was trying to convert the String into char array first and then printing each character backwards in the console using for loop. However, I need to save the value in a String now that I can't seem to figure out.
This is the code here:
var answer = document.getElementById("ta").value;
var arr = answer.split("");
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str = arr[i];
console.log(str); //it works but displays each character individually
}
I just want all the characters in a String. Please help! Brevity in the answer would be appreciated
JavaScript unlike other oops, provide an inherited reverse function that reverses array. So one answer to this whould be:
let arr = answer.split("") //note this creates an array with each char as element of array
arr = arr.reverse(); //this reverses the array
let string = arr.join(""); //this joins the array into a single string
Another method would be the one you are trying to do, create your own reverse function. You are doing it all right but just missing a step, that is to join the array, you are simply printing each letter of the array and thats the property of console.log that each console.log prints to a new line. That explains why you are getting it all in new line.
var answer = document.getElementById("ta").value;
var arr = answer.split("");
var str ="";
for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
str =str + arr[i];
}
console.log(str); //it should be outside the loop and print string once it has been formed
P.S:I have given as much detail I can on this to get you started but this is a very basic question and doesnt deserve to be here, you should follow some basic concepts of js on mdn or w3schools. Plus google your problems before turning to stackoverflow.
If you want to put all the characters in str you can try this way:
str= str+arr[i]
or try this way:
var str = "";
arr.forEach(element => {str= str+element});
console.log(str)

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

Regex one-liner for splitting string at nth character where n is a variable length

I've found a few similar questions, but none of them are clean one-liners, which I feel should be possible. I want to split a string at the last instance of specific character (in my case .).
var img = $('body').attr('data-bg-img-url'); // the string http://sub.foo.com/img/my-img.jpg
var finalChar = img.split( img.split(/[.]+/).length-1 ); // returns int 3 in above string example
var dynamicRegex = '/[.$`finalChar`]/';
I know I'm breaking some rules here, wondering if someone smarter than me knows the correct way to put that together and compress it?
EDIT - The end goal here is to split and store http://sub.foo.com/img/my-img and .jpg as separate strings.
In regex, .* is greedy, meaning it will match as much as possible. Therefore, if you want to match up to the last ., you could do:
/^.*\./
And from the looks, you are trying to get the file extension, so you would want to add capture:
var result = /^.*\.(.*)$/.exec( str );
var extension = result[1];
And for both parts:
var result = /^(.*)\.(.*)$/.exec( str );
var path = result[1];
var extension = result[2];
You can use the lastIndexOf() method on the period and then use the substring method to obtain the first and second string. The split() method is better used in a foreach scenario where you want to split at all instances. Substring is preferable for these types of cases where you are breaking at a single instance of the string.

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]);
}

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