Shift js string one character - javascript

In PHP, it's pretty simple, I'd assume, array_shift($string)?
If not, I'm sure there's some equally simple solution :)
However, is there any way to achieve the same thing in JavaScript?
My specific example is the pulling of window.location.hash from the address bar in order to dynamically load a specific AJAX page. If the hash was "2", i.e. http://foo.bar.com#2...
var hash = window.location.hash; // hash would be "#2"
I'd ideally like to take the # off, so a simple 2 gets fed into the function.
Thanks!

hash = hash.substr(1);
This will take off the first character of hash and return everything else. This is actually similar in functionality to the PHP substr function, which is probably what you should be using to get substrings of strings in PHP rather than array_shift anyway (I didn't even know array_shift would work with strings!)

As you suspected, there's also a shift() function on the Array prototype (MDN).
Strings are not Arrays, they are "array-like objects" so to call shift() on a String, it must be split() first:
var arr = str.split("");
var char = arr.shift();
var originalString = arr.join("");

Building on Ben's point regarding conversion to an Array, given that we are assuming there is only one character as the hash, and that it is the last character, we should really just use:
var hash = window.location.split("").pop();

Related

regular expression to split string avoiding double tokens

In order to split a string value into an array using javascript I need to split using delimiters. Repeated delimiters indicate a sub-value within the array, so for example
abc+!+;def+!+!+;123+!+;xyz
should split into abc, [def, 123], xyz
My nearest expression is ((?:+!(?!+!))+\;|$) but thinking about it that may be the one I first started with, as I've gone through so many many variations since then.
There is probably a blindingly obvious answer, but after what seems an eternity I'm now stumped. I took a look at regex to parse string with escaped characters, and similar articles which were close although not the same problem, but basically came to a stop with ideas.
Somewhere out there someone will know regular expressions far better than I do, and hope that they have an answer
I got this to work by using .split() with this basic pattern:
\b\+!\+;\b
And then:
\b\+!\+!\+;\b
And so on, and so forth. You will need to turn this into a recursive function, but I made a basic JSFiddle to get you started. First we split the string using our first expression. Then we create our newer expression by adding !\+ (this can easily be done dynamically). Now we can loop through our initial array, see if the string matches our new expression and if it does split it again.
var string = 'abc+!+;def+!+!+;123+!+;xyz',
data = string.split(/\b\+!\+;\b/);
var regex = /\b\+!\+!\+;\b/
for(var i = 0; i < data.length; i++) {
var string = data[i];
if(string.match(regex)) {
data[i] = string.split(regex);
}
}
console.log(data);
// ["abc", ["def", "123"], "xyz"]
I'm leaving the task of making this a recursive function up to OP. If you want some direction, I can try to provide some more insight.

Array to string in JavaScript

I get an array of numbers as a response from remote command execution (using ssh2). How do I convert it to a string?
[97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]
var result = String.fromCharCode.apply(null, arrayOfValues);
JSFiddle
Explanations:
String.fromCharCode can take a list of char codes as argument, each char code as a separate argument (for example: String.fromCharCode(97,98,99)).
apply allows to call a function with a custom this, and arguments provided as an array (in contrary to call which take arguments as is). So, as we don't care what this is, we set it to null (but anything could work).
In conclusion, String.fromCharCode.apply(null, [97,98,99]) is equivalent to String.fromCharCode(97,98,99) and returns 'abc', which is what we expect.
It depends on what you want and what you mean.
Option One: If you want to convert the text to ASCII, do this:
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
theString = String.fromCharCode.apply(0, theArray);
(Edited based on helpful comments.)
Produces:
app.js
node.js
Option Two: If you just want a list separated by commas, you can do .join(','):
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var theString = theArray.join(',');
You can put whatever you want as a separator in .join(), like a comma and a space, hyphens, or even words.
In node.js it's usually done with buffers:
> new Buffer([97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]).toString()
'app.js\nnode.js\n'
It'll be faster than fromCharCode, and what's most important, it'll preserve utf-8 sequences correctly.
just use the toString() function:
var yourArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var strng = yourArray.toString();
The ssh2 module passes a Buffer (not an actual javascript array) to 'data' event handlers for streams you get from exec() or shell(). Unless of course you called setEncoding() on the stream, in which case you'd get a string with the encoding you specified.
If you want the string representation instead of the raw binary data, then call chunk.toString() for example.

Comparing Strings to find Missing Substrings

I am working a serviceNow business rule and want to compare two strings and capture the substrings that are missing from the string for example...
var str1 = "subStr1,subStr2,subStr3,subStr4"
var str2 = "subStr1,subStr3"
magicFunction(str1,str2);
and the magic function would return "subStr2,subStr4"
I'd probably have better luck turning the strings into arrays and comparing them that way which if there is some method that would be recommended I can do that, but I have to push a , separated string back to the form field for it to work right, something with how sys_id's behave seems to demand it.
Basically I have a field on a form that holds a list of sys_ids, I need if one of those sys_ids is removed from the list I can capture the sys_id and make some change on the record belonging to it
If you're not against using libraries, underscore has an easy way to do this with arrays. See http://underscorejs.org/#difference
function magicFunction(str1, str2) {
return _.difference(str1.split(","),str2.split(",")).join(",");
}
The ArrayUtil Script Include in ServiceNow has a "diff" function, once you use split(",") on your Strings to create two Arrays.
e.g.,
var myDiffArray = new ArrayUtil().diff(myArray1, myArray2);
Assuming you're list has commas separating them, you can use split(",") and join(",") to turn them in to arrays/back into comma delimited lists, and then you can find the differences pretty easily using this method of finding array differences.

Get part of string?

I have a string formatted like this:
item_questions_attributes_abc123_id
I'm specifically trying to get the abc123 bit. That string can be any alphanumeric of any case. No special characters or spaces.
I'm using jQuery, though I'm certainly fine with using straight javascript if that's the best solution.
If it's always the 4th part of the string you can use split.
var original = 'item_questions_attributes_abc123_id';
var result = original.split('_')[3];
Try this:
var myArray = myString.split("_");
alert(myArray[3]);
use split method of javascript and then use 2nd last index you will have your required data.

please extract a bit of info from this string (without regex so that i can understand it)

On my web app, I take a look at the current URL, and if the current URL is a form like this:
http://www.domain.com:11000/invite/abcde16989/root/index.html
-> All I need is to extract the ID which consists of 5 letters and 5 numbers (abcde16989) in another variable for further use.
So I need this:
var current_url = "the whole path, not just the hostname";
if (current_url has ID)
var ID = abcde16989;
You could always use split using / as the delimiter if the ID is always going to be in the same position, eg
var parts = current_url.split('/');
var id = parts[4];
Though your requirement of matching "5 letters and 5 numbers" really does suit a regex match.
var id = current_url.match(/[a-zA-Z]{5}[0-9]{5}/); // returns null if not found
I'm assuming you don't need the full URL, but just the pathname to get your ID. Use the following:
var current_url = window.location.pathname; //gets the pathname
var split_url = current_url.split('/'); //splits the path at each /
current_id = split_url[2]; //1st item in array is "invite", 2nd is your id, 3rd would be "root"
alert(current_id);
Firstly, this doesn't need JQuery; this is simple Javascript. I'll amend your tags after I've replied to reflect this.
A regex would actually be quite an easy way to achieve this, and I don't think a simple one like this would be as difficult to understand as you think.
So I'll answer with the regex option anyway and then move on to other options:
var url = "http://www.domain.com:11000/invite/abcde16989/root/index.html";
//first method:
var id = url.match('^http://www.domain.com:11000/invite/(.+)/root/index.html$')[1];/index.html$/)[1];
//second method: (if you don't know exact format of the rest of the URL but you do know the format of the ID string)
var id = url.match('/([a-z]{5}[0-9]{5})/')[1];
The first method will get the string in the position you specified within the URL. It won't check the formatting; it just looks at the rest of the URL and grabs the bit of it you're asking for. This should be really easy to understand: It's basically just your URL, but with (.+) where your ID goes.
The second method looks specifically for a string in the format you asked for -- ie five letters and then five numbers. This is admittedly a bit harder to read, but should be fairly self explanatory if you look at it given those criteria.
In both cases, the regex itself will return an array of results, with array element zero being the whole string (ie in the first case, including the rest of the URL). This is where the (brackets) come in (ie the bit where we said (.+)). This tells the match function to put the contents of the brackets into another array element so we can use it. In both cases, this means that we can read the ID in array element [1].
Okay, so how about the non-regex options:
In fact, it's going to be quite hard to do it in a simple way without regex in Javascript, since even the simple string splitting function uses a regex match to do the split (granted it would be a very simple one, it is still a regex). A couple of other people have already given you answers using this, but it is still a regex, so technically they've also not answered your question accurately.
I'm going to guess that actually one of these answers will be good enough for you (either mine or more likely one of the answers using split()), despite there still being a regex element. However if you really don't want anything to do with regex, you're going to have to start doing some slightly more complex string manipulation, probably using substring() (though there are other ways to do it).
Something along the lines of this:
var prefixstring="http://www.domain.com:11000/invite/";
var prefixlen=prefixstring.length;
var idlen=10;
var id = url.substring(prefixlen,idlen+prefixlen);
This gets the length of the portion of the URL in front of the ID, and then uses substring() to snip out the required bit. But I'm sure you'll agree that the regex options are simpler? ;-)
Hope that helps. (and I hope it helps you feel less afraid of regex!)

Categories

Resources