split javascript string to get desired values - javascript

I want to extract the date and the username from string using .split() in this particular string:
var str ='XxSPMxX on 08/30/2012';
I want XxSPMxX in one variable and 08/30/2012 in the other.

Using just split:
var x = str.split('</a> on ');
var name = x[0].split('>')[1];
var date = x[1];
Demo: http://jsfiddle.net/Guffa/YUaAT/

I don't think split is the right tool for this job. Try this regex:
var str ='XxSPMxX on 08/30/2012',
name = str.match(/[^><]+(?=<)/)[0],
date = str.match(/\d{2}\/\d{2}\/\d{4}/)[0];
Here's the fiddle: http://jsfiddle.net/5ve7Y/

Another way would be to match using a regular expression, build up a small array to get the parts of the anchor, and then use substring to grab the date.
var str = 'XxSPMxX on 08/30/2012';
var matches = [];
str.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
matches.push(Array.prototype.slice.call(arguments, 1, 4))
});
var anchorText = matches[0][2];
var theDate = str.substring(str.length - 10, str.length);
console.log(anchorText, theDate);
working example here: http://jsfiddle.net/dkA6D/

Related

delete character at back

12:00:00:12
How to remove 6 character from the back? the output would be 12:00, I can't use substring to get the from the front to get the 6 char, because it can be 9:00 so it's just 4 char instead of 5.
I think #ZakariaAcharki is a better solution but if you want make it by substring try this:
str = '12:00:00:12';
str.substring(0,str.length-6);
I think better if you use split() function, and take the first and second items in splited array.
var my_string ="12:00:00:12";
var array_splited = my_string.split(':');
console.log( array_splited[0] + ':' + array_splited[1] ); //12:00
If you want it in single line, e.g :
my_string.split(':')[0] + ':' + my_string.split(':')[1];
Hope this helps.
You can determine the length and than go back 6 chars e.g.
str = '12:00:00:12'
str = str.substring(0,str.length - 6);
But you may better match with
str = '12:00:00:12'.match(/^[0-9]+:[0-9]+/)[0]
A regular expression with .match() method will do:
var str1 = '12:00:00:12';
var str2 = '9:40:00:12';
var regex = /(\d+)+:+(\d\d)/g;
var newStr1 = str1.match(regex)[0];
var newStr2 = str2.match(regex)[0];
document.querySelector('#one').textContent = JSON.stringify(newStr1);
document.querySelector('#two').textContent = JSON.stringify(newStr2);
'12:00:00:12' <pre id='one'></pre>
<hr>
'9:40:00:12' <pre id='two'></pre>
var str = "12:00:00:12";
var newStrArr = str.split(":");
newStrArr.pop();
newStrArr.pop();
newStrArr.join(":");
If the time will always be in the form (0-12):(00-59);(00-59) then you could use regex and the function .match() to get the time in the format you would like:
current_time = '12:00:00'
time_formatted = current_time.match(/\d+:\d+/)
Try using split and join.
EG 1:
var num = "12:00:00:12";
console.log(num.split(':', 2).join(':'));
EG 2:
var num = "9:00:00:12";
console.log(num.split(':', 2).join(':'));
Simple and best solution:
Use slice() function.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(function(){
var str = '12:00:00:12';
alert(str.slice(0,-6));
});
Output: 12:00
JSFiddle Demo

Incrementing a number in a string

I have the following string: 0-3-terms and I need to increment the 3 by 20 every time I click a button, also the start value might not always be 3 but I'll use it in this example..
I managed to do this using substring but it was so messy, I'd rather see if it's possible using Regex but I'm not good with Regex. So far I got here, I thought I would use the two hyphens to find the number I need to increment.
var str = '0-3-terms';
var patt = /0-[0-9]+-/;
var match = str.match(patt)[0];
//output ["0-3-"]
How can I increment the number 3 by 20 and insert it back in to the str, so I get:
0-23-terms, 0-43-terms, 0-63-terms etc.
You're doing a replacement. So use .replace.
var str = '0-3-terms';
var patt = /-(\d+)-/;
var result = str.replace(patt,function(_,n) {return "-"+(+n+20)+"-";});
Another option is to use .split instead of regex, if you prefer. That would look like this:
var str = '0-3-terms';
var split = str.split('-');
split[1] = +split[1] + 20;
var result = split.join('-');
alert(result);
I don't understand why you are using regex. Simply store the value and create string when the button is called..
//first value
var value = 3;
var str = '0-3-terms';
//after clicking the button
value = value+20;
str = "0-" + value + "-terms"

Replace a string of the last 7 chars?

This is my code :
​var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
and I'd like to replace the last 7 chars (med.png) with big.png. Or, as you can see, the last occurence after a - split.
How can I do it? I think about regex, but I'm not a champion with them. Tried :
myStr = myStr .replace(/-([^-]*)$/, "big" + '$1');
but it replace the last -, not the last occurence. So the result is /private_images/last-edit/image-workbigmed.png
I'll make a confession: I'm not so great with regexes either.
How about splitting up using split? Less concise, but easier to understand.
var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
var strs = myStr.split('-');
// Change the last element.
strs[strs.length - 1] = "big.png";
// And put back the right string.
myStr = strs.join('-');
You could use a regex, or you could use a few string methods and make your intentions clear.
var idx = myStr.lastIndexOf("-");
var newStr = myStr.substring(0, idx) + "big.png";
Without using RegExp you could use:
var str = "/private_images/last-edit/image-work-med.png"
,replace = 'big.png'
,nwstr = str.slice(0,str.lastIndexOf('-')+1)+replace;
//=> nwstr now "/private_images/last-edit/image-work-big.png"
More 'functional':
var nwstr = function(s){
return s.replace(s.substr(-7),'');}(
'/private_images/last-edit/image-work-med.png'
)+'big.png'
var url = "/private_images/last-edit/image-work-med.png";
var index = url.lastIndexOf('-');
url = url.substring(0, index+1);
var url2 = "big.png";
var output = url.concat(url2); alert(output);
Check this
Just add '-' to your regex and to the replacement string:
myStr = myStr .replace(/-([^-]*)\.png$/, "-big.png");
Or if you want the file extension to be variable:
myStr = myStr .replace(/-([^-]*)\.([a-z]+)$/, "-big.$2");
Why not just use replace:
var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
var newStr = myStr.replace("med.png", "big.png");
According to the requirements specified in your question this would suffice.
If you know it will be a .png file:
var ex = new Regex(#"-\w*.png$");
var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
myStr = ex.Replace(myStr, "-big.png");
It works but if its a jpg it wont...
If you want to use string functions -
var myStr = "/private_images/last-edit/image-work-med.png";
var cleanedupStr = myStr.slice(0, myStr.lastIndexOf("-"));
String.slice

split string to two substrings from nth occerence of a charactor jquery

i have a string like this .
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11"
i want to get substrings
http://localhost/elephanti2/chaink/stores/stores_ajax_page
and
5/b.BusinessName/asc/1/11
i want to split string from the 7 th slash and make the two sub-strings
how to do this ??,
i looked for split()
but in this case if i use it i have to con-cat the sub-strings and make what i want . is there a easy way ??
try this one:
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var parts = url.split('/');
var p1 = parts.slice(0,6).join('/');
var p2 = parts.slice(7).join('/');
alert(p1);
alert(p2);
p1 should get the first part and p2 is the second part
You can try this regex. Generally if your url pattern always follow this structure, it will work.
var pattern = /(\w+:\/\/(\w+\/){5})/i;
var url = "http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var result = url.split(pattern);
alert(result[1]);
alert(result[3]);
Try this :
var str = 'http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11',
delimiter = '/',
start = 7,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter);
var match = str.match(/([^\/]*\/){5}/)[0];
Find this fiddle

How do I split this string with JavaScript?

Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);

Categories