Delete last 8 characters out of string in Jquery - javascript

I have some output data from an ajax call and I would like to take out the last 8 characters of the data but also delete them out of that string that when I print out the data, the string I have taken would not show up.
Here is the code I have tried, It successfully takes that last 8 characters but does not remove them.
var data = "This is some data 12345678";
var comment_id = data.slice(-8);
jQuery.trim(comment_id);
$('#comments_'+comment_id).html(data);

var comment_id = data.slice(-8);
this line will not change the value of data it will only take out last 8 characters from the data. data is a string and it is immutable
add the following line after this line
data = data.substring(0, data.length -8);

Return json from server side code
{message:"This is some data",comment_id:"12345678"}
You can access it like
$('#comments_'+data.comment_id).html(data.message);

Why not substring?
var strLen=data.length,
comment_id=data.substring((strLen>=8?strLen-8:0),strLen);
(ignore this part of my answer)
To remove them, do almost the same:
data=data.substring(0,strLen-8)
Equivalent of:
"daddaddad" to "d"
(I didn't note you was wanting that, so I'm sorry)

Here's a nice approach using regex that's a bit cleaner too:
var data = "This is some data 12345678",
comment_id = data.match(/\d{8}$/)[0];
data = data.replace(comment_id, '').trim();
$('#comments_' + comment_id).html(data);

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

how to replace part of part of string in javascript

I have two GUIDs. I am looking for to replace c013d94e from 1st guid with cd11d94e of second guid in Javascipt.
I checked javascript replace() method but not sure how i can use it with my specific case.
c013d94e-3210-e511-82ec-303a64efb676 - 1st Guid
cd11d94e-3210-e511-82ec-303a64efb676 - 2nd Guid
Following is my code where i am trying to do it
for(var i=0; i < response[1].length;i++)
angular.forEach($scope.studentPermissions[i][0].Children, function (subject) {
string 1stGuid= response[1].data[i].Id; // it contains cd11d94e-3210-e511-82ec-303a64efb676
subject.Id = // it contains c013d94e-3210-e511-82ec-303a64efb676
});
replace takes 2 parameters, the first is the string to search for and the second is the replacement string. It doesn't modify the original string, it simply returns a new string with the value replaced.
You can perform your replace like this:
var guid = 'c013d94e-3210-e511-82ec-303a64efb676';
guid = guid.replace('c013d94e', 'cd11d94e');
console.log(guid); // 'cd11d94e-3210-e511-82ec-303a64efb676'
#Jamen. Yes the other part of 1st string will always be same. How can i use concatenate?
You don't even need to use replace then? Just make a brand new string:
var guid = "cd11d94e-3210-e511-82ec-303a64efb676";
But, to actually answer the question in the title:
var input = "c013d94e-3210-e511-82ec-303a64efb676";
var output = input.replace("c013d94e", "cd11d94e");
console.log(output); // cd11d94e-3210-e511-82ec-303a64efb676
But like I said, in your situation this shouldn't be necessary, based on the quote.

string to array - javascript

I am reading the plain text file in node.js using ajax call from client side.
Result :
success gives the result as below.
""[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n""
After parsing the above result :
JSON.parse(result);
"[{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}] [{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}] "
I want to change this string to array of objects,
Expected Result is array of objects:
[{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6},
{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}
]
Ajax call Code
$.ajax({
url: document.URL + "getData",
method : "GET",
success: function (result) {
var info = JSON.parse(result);
var object = JSON.parse(info);
console.log(object);
}
});
Any idea will be helpful.
That is some seriously messed-up JSON. There's an extra quote mark at each end, and ]\n[ in the middle where there should be a ,.
You really should fix your server to generate valid JSON, but if you can't, you could tweak it like this:
var res = '"[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n"';
var resfix = res.replace( /^"|"$/g, '' ).replace( ']\n[', ',' );
JSON.parse( resfix );
I changed the extra set of quotes at the very outside of your var res = string to make it a valid JavaScript string for testing.
It looks to me like you've simply got double-encoded JSON. Just run it through JSON.parse() a second time.
EDIT actually, that's not quite right - the output contains two JS arrays, with a \n separator and no enclosing array. You will have to manipulate the data a bit (looking at that now) to make it parseable a second time.
EDIT2 This appears to work, albeit that your current var res line includes an extra pair of surrounding quotes that aren't legal so in this test I've removed them:
var res = "[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n"
var out = JSON.parse(res.replace(/]\s*\[/g, ','));

JS Regex match string with $

I am trying to write something that would look at tweets and pull up info about stocks being mentioned in the tweet. People use $ to reference stock symbols on twitter but I cant escape the $.
I also dont want to match any price mention or anything like that so basically match $AAPL and not $1500
I was thinking it would be something like this
\b\$[a-zA-Z].*\b
if there are multiple matches id like to loop through them somehow so something like
while ((tweet = reg.exec(sym_pat)) !== null) {
//replace text with stock data.
}
This expression gives me an unexpected illegal token error
var symbol_pat = new RegExp(\b\$[a-z]*);
Thanks for the help if you want to see the next issue I ran into
Javascript AJAX scope inside of $.each Scope
Okay, you've stated that you want to replace the matches with their actual stock values. So, you need to get all of the matching elements (stock ticker names) and then for each match you're going to replace the it with the stock value.
The answer will "read" very similarly to that sentence.
Assume there's a tweet variable that is the contents of a particular tweet you're going to work on:
tweet.match(/\b\$[A-Za-z]+\b/g).forEach(function(match) {
// match looks like '$AAPL'
var tickerValue = lookUpTickerValue(match);
tweet.replace(match, tickerValue);
});
This is assuming you have some logic somewhere that will grab the ticker value for the given stock name and then replace it (it should probably return the original value if it can't find a match, so you don't mangle lovely tweets like "Barbara Streisand is $ATAN").
var symbol_pat = new RegExp('\\b\\$[a-z]+\\b','gi');
// or
var symbol_pat = /\b\$[a-z]+\b/gi;
Also, for some reason JS can not calculate the beginning of a word by \b, it just catches the one at the end.
EDIT: If you're replacing the stock symbols you can use the basic replace method by a function and replace that data with predefined values:
var symbol_pat = /(^|\s)(\$[a-z]+\b)/gi;
var stocks = {AAPL:1,ETC:2}
var str = '$aapl ssd $a a$s$etc $etc';
console.log(str);
str = str.replace(symbol_pat, function() {
var stk = arguments[2].substr(1).toUpperCase();
// assuming you want to replace $etc as well as $ETC by using
// the .toUpperCase() method
if (!stocks[stk]) return arguments[0];
return arguments[0].replace(arguments[2],stocks[stk]);
});
console.log(str);

Categories