How to read only part of a string in Javascript - javascript

I am pulling in a string from another web page. I want to read that string into a variable but only after a certain point. Eg:
#stringexample
var variable;
I want variable to equal stringexample but not contain the # how could I do this?
This is how I am using the variable at the moment.
$("#Outputajax").load("folder/"+ variable +".html");
This is the way that works but isn't a variable.
$("#Outputajax").load("folder/webpage.html");

If you just want to trim of the first character, then you can use substring...
var input = "#stringexample";
input = input.substring(1);
//input = "stringexample"
Here is a working example

var myVariable = stringExample.replace('#','');

Could just use variable.substr(1) to cut off the first character.
If you want to specifically remove the hash from the start (but do nothing if the hash isn't there), try variable.replace(/^#/,"")

I understand you want to get everything in the string AFTER the hashtag. The other solutions will leave anything ahead of the hashtag in as well. And substring does not work if the hashtag is not the first symbol.
variable= "#stringexample".split("#")[1];
This splits the string into an array of strings, with the parameter as the point where to split, without including the parameter itself. There will be an empty string as the first parameter, and everything after the hashtag is the second string.

var slicer = function(somestring){
var parsedString = somestring;
parsedString = parsedString.slice(1);
return parsedString
}
// run from yors function with some string
var someYouVar = slicer("#something")

Related

MongoDB Search, Skip Special Characters

Suppose a field(version) contains value 1.12.34 or 10.2.3.5 or any string which contains . at any position. So is there is any way to get the document by searching for 11234 or 10235, basically without . in the string.
You can use regex to solve this problem
var str = '1.12.34'
var newString = str.replace(/[^0-9]+/ig, "");
console.log(newString)
Here is an example.
So you can use your version field with replace function using the regex, don't need another field to store version value without dot(.)

Is there a more succinct way to get the last number in my url?

So I currently pass two variables into the url for use on another page. I get the last variable (ie #12345) with location.hash. Then from the other part of the url (john%20jacob%202) all I need is the '2'. I've got it working but feel there must be a cleaner and succinct way to handle this. The (john%20jacob%202) will change all the time to have different string lengths.
url: http://localhost/index.html?john%20jacob%202?#12345
<script>
var hashUrl = location.hash.replace("?","");
// function here to use this data
var fullUrl = window.location.href;
var urlSplit = fullUrl.split('?');
var justName = urlSplit[1];
var nameSplit = justName.split('%20');
var justNumber = nameSplit[2];
// function here to use this data
</script>
A really quick one-liner could be something like:
let url = 'http://localhost/index.html?john%20jacob%202?#12345';
url.split('?')[1].split('').pop();
// returns '2'
How about something like
decodeURI(window.location.search).replace(/\D/g, '')
Since your window.location.search is URI encoded we start by decoding it. Then replace everything that is not a number with nothing. For your particular URL it will return 2
Edit for clarity:
Your example location http://localhost/index.html?john%20jacob%202?#12345 consists of several parts, but the interesting one here is the part after the ? and before the #.
In Javascript this interesting part, the query string (or search), is available through window.location.search. For your specific location window.location.search will return ?john%20jacob%202?.
The %20 is a URI encoded space. To decode (ie. remove) all the URI encodings I first run the search string through the decodeURI function. Then I replace everything that is not a number in that string with an empty string using a regular expression.
The regular expression /\D/ matches any character that is not a number, and the g is a modifier specifying that I want to match everything (not just stop after the first match), resulting in 2.
If you know you are always after a tag, you could replace everything up until the "#"
url.replace(/^.+#/, '');
Alternatively, this regex will match the last numbers in your URL:
url.match(/(?<=\D)\d+$/);
//(positive look behind for any non-digit) one more digits until the end of the string

Get the file name from Css propery background url

$('.icon-displayer').css('background-image');
console.log(a)
gives me value as url("http://localhost:8080/myApp/icons/xing-square.png")
from this string i want extract only the file name i.e xing-suare.png how do i do it?
I tried
var url= $('.icon-displayer').css('background-image');
var filename = url.split('/').pop()
did not work
Javascript pop method remove the last element from an array. Use split and then get the last position of the array.
var url= $('.balaIconPicker-icon-displayer').css('background-image');
var array = url.split('/');
var filename = array[array.length - 1];
If there are no parameters, then Lucas's answer is okay and it's the one you should use. However if the string at the end is something like "test.php?id=125" you will get the "?id=125" too which may not be what you want. A regular expression can save you from this:
var url = "http://www.test.com/directory/test.php?id=128",
cleanRegexp = /\/([^\.\/]+\.[a-z]{0,3})[^\/]*$/;
var result = cleanRegexp.exec(url);
window.alert(result[1]);
the regular expression finds the last slash, then looks after it for anything that isn't a slash or a dot, then grabs the dot and the extension, finishing before any special characters.
Here is the Fiddle

Parsing Text with jQuery

I'm attempting to parse a text string with jQuery and to make a variable out of it. The string is below:
Publications Deadlines: armadllo
I'm trying to just get everything past "Publications Deadlines: ", so it includes whatever the name is, regardless of how long or how many words it is.
I'm getting the text via a the jQuery .text() function like so:
$('.label_im_getting').text()
I feel like this may be a simple solution that I just can't put together. Traditional JS is fine as well if it's more efficient than JQ!
Try this,
Live Demo
First part
str = $.trim($('.label_im_getting').text().split(':')[0]);
Second part
str = $.trim($('.label_im_getting').text().split(':')[1]);
var string = input.split(':') // splits in two halfs based on the position of ':'
string = input[1] // take the second half
string = string.replace(/ /g, ''); // removes all the spaces.

javascript replace not workings

I've got a problem with replace not working.
alert($('input#membership_edc').next("label").html().replace(/£/g, ""));
The value of the label after the input would be £24.00, but I want to do a math on that value then put it back with the new value. It's not removing the pound sign.
What's wrong? Thanks.
To read/modify/write use the function parameter version of .html():
$('input#membership_edc').next("label").html(function(index, old) {
var n = parseFloat(old.replace('£', '');
return n + 10;
});
would replace '£24.00' with '34'.
You need to set the value returned from the replace. Try below,
var $label = $('input#membership_edc').next("label");
$label.html($label.html().replace(/£/g, ""));
Nothing wrong. It is working here.
Are you sure your markup is fine?
The string replace function returns a new string. Strings themselves are immutable in javascript, I think. As Vega has it:
// avoid looking this up twice
var label = alert($('input#membership_edc').next("label");
// replace and assign
label.html(label.html().replace(/£/g, ""));
Edit:
To get the numerical value from the string:
var amount = alert($('input#membership_edc').next("label").html().match(/£\s*([-0-9.]+)/)[1];
This matches the numbers etc after the £ (ignoring whitespace), and uses index 1 from the array, containing the contents of the first group match (in the brackets).
" £1.45".match(/£\s*([-0-9.]+)/)[1]; // returns "1.45"
Beware that it is still a string, so you might want to do parseFloat on it.

Categories