How to get/remove string and the char before from object? - javascript

So i have this object of photos, which is value of some hidden input:
53bd570ba13ef.jpg,53bd570c964c3.jpg,53bd570d311c9.jpg,53bd570db8997.jpg.
What i need is to remove last string witch number and the comma before: ,53bd570db8997.jpg.
var dataInput = $('#images'),
imgs = dataInput.val(),
thumbIndex = $(this).parent().index();
//
var _result = imgs.split(',')[thumbIndex];
//
var name = _result.slice(0, _result.indexOf(","));
console.log(name);
The thumbIndex is my photo number/name without the comma: 53bd570db8997.jpg. Can anybody help?

If I understood you right, I'd regexp it:
imgs.replace(new RegExp("," + thumbIndex),"");
imgs should be the string you posted above (the comma-separated one).

If you're sure that thumbIndex contains the last filename, you can get away with this:
var data = '53bd570ba13ef.jpg,53bd570c964c3.jpg,53bd570d311c9.jpg,53bd570db8997.jpg'; // or $('#images').val()
var thumbIndex = '53bd570db8997.jpg';
var result = data.substr(0, data.indexOf(thumbIndex) - 1);

Perhaps you could elaborate a little bit more on what precisely you want to achieve, but I'm going to make an attempt at understanding your question and I will try to give you a solution.
As I understand, you wish to get the last element from a string of values which are delimited by a ',' character.
You could of course split the string and simply get the last element from the array.
var dataInput = $('#images');
var imgs = dataInput.val();
var _result = imgs.split(',');
var thumbnail = _result[_result.length - 1];
console.log(thumbnail);
Here's a JSFiddle to try out: http://jsfiddle.net/WBb5F/1/

If I got you right, you can try lastIndexOf()
var result = data.substr(0, data.indexOf(','));
Fiddle

Using this html
<input type="hidden" value="53bd570ba13ef.jpg,53bd570c964c3.jpg,53bd570d311c9.jpg,53bd570db8997.jpg" id="images" />
To get the last item you can do this:
var dataInput = $('#images'),
imgs = dataInput.val(),
thumbIndex = imgs.split(',').length;
var name = imgs.split(',')[thumbIndex - 1]
console.log(','+ name);
Here is the FIDDLE

Related

How to remove `&` sign and all text after that from url

I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).

How can I extract a part of this url with JavaScript?

I have an url that looks like this:
http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg
I want to extract hw6dNDBT.jpg, from the url above.
I tried playing around with regex patterns /img\/.*-/ but that
matches with img/hw6dNDBT-.
How can I do this in JavaScript?
try this:
var url = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
var filename = url.match(/img\/(.*)-[^.]+(\.[^.]+)/).slice(1).join('');
document.body.innerHTML = filename;
i would use split() method:
var str = "http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg";
var strArr = str.split("/");
var size = strArr.length - 1;
var needle = strArr[size].split("-");
var fileTypeArr = strArr[size].split(".");
var name = needle[0]+"."+fileTypeArr[fileTypeArr.length-1];
name should now be your searched String so far it contains no / inside it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
/[^\/]+$/ should match all characters after the last / in the URL, which seems to be what you want to match.
No regex:
//this is a hack that lets the anchor tag do some parsing for you
var parser = document.createElement('a');
parser.href = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
//optional if you know you can always trim the start of the path
var path = parser.pathname.replace('/assets/uploads/');
var parts = path.split('/');
var img = '';
for(var i=0; i<parts.length; i++) {
if (parts[i] == 'img') {
//since we know the .jpg always follows 'img/'
img = parts[i+1];
}
}
Ah, you were so close! You just need to take your regex and use a capturing group, and then add a littttle bit more!
img\/(.*)-.*(\..*)
So, you can use that in this manner:
var result = /img\/(.*)-.*(\..*)/.exec();
var filename = result[1] + result[2];
Honestly capturing the .jpg, is a little excessive, if you know they are all going to be JPG images, you can probably just take out the second half of the regex.
Incase you are wondering, why do we uses result[1] and result[2]? Because result[0] stores the entire match, which is what you were getting back. The captured groups, which is what we create when we use the parentheses, are stored as the indexes after 0.
Here is some one-liner:
var myUrl = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg',
myValue = myUrl.split('/').pop().replace(/-(?=\d).[^.]+/,'');
We take everything after the last slash then cut out the dimension part.

get only the last match? .match(word)

I have a regex to get #user from a textarea. When user type something with # I get it.
My problem is, I want to get just the last match, not all of them.
eg:
user type:
#josh and #marie = want to show #marie
#josh loves #marie and #anne = show #anne
my code is showing like this:
#josh,#marie,#anne
Can I get just the last #something entry? (while user is typing)
var word=/#(\w+)/ig;
$("#comment").on("keyup",function() {
var content = $(this).val();
var name = content.match(word);
var dataString = name;
if(name.length > 0) {
$("#result").text(name);
}
return false();
});
html
<textarea id=comment>#josh and #marie</textarea>
<div id=result></div>
https://jsfiddle.net/dcs5pat8/ (press on textarea)
Besides getting all matches and obtain the last one, you can use capture groups to get the last match:
var word=/.*(#\w+)/i;
var name = content.match(word)[1];
Or using exec, the whole would look like:
var word=/.*(#\w+)/i;
$("#comment").on("input",function() { //changed keyup to input
var content=$(this).val();
var match = word.exec(content);
if(match){
$("#result").text(match[1]);
}
});
Fiddle
PS, if your goal is a more generic approach and you need to switch between getting all words and a single one, I'd recommend keeping the global match and getting the last as in Jonas' answer.
My suggestion is that you show only the last entry of your results.
You can do that by changing the line:
var name = content.match(word);
to
var names = content.match(word);
var name = names[names.length - 1];
On more detail, what this does is it gets all the results from your regex, then it attributes the last item of the array to the name variable.
Hope this was helpful.
You can simply select or pop the last match in the array of match returned by .match()
var word=/#(\w+)/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var matches = content.match(word);
var lastmatch = matches.pop();
//IF YOU NEED TO KEEP INTACT THE VAR MATCHES
//var lastmatch = matches[matches.length - 1];
if(name.length>0){
$("#result").text(lastmatch);
}
return false();
});
JSFiddle
Use this regex '/#(\w+)$/ig' insted of '/#(\w+)/ig'.
And then your code will run like a charm. ;)
var word=/#(\w+)$/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var name = content.match(word);
var dataString = name;
if(name.length>0){
$("#result").text(name);
}
return false();
});
See it hear https://jsfiddle.net/dcs5pat8/1/
I do like the answer where you take your list with all of the #names,#name1,#name2 and just split off the last one, but here it is in just one step
//split on #something
//the penultimate item is our target
//if there is < 2 items there weren't any #somethings so return ''
user = (split = "testing #charlie testing".split(/(#[^ ]*)/)).length > 1 ? split.splice(-2,1)[0] : '';
https://jsfiddle.net/ek19h0fb/1/
To have only one line you can do
var name = content.match(word).reverse()[0];

How to truncate certain text in javascript

I have following INPUT out.
pieChart.js
stackedColumnChart.js
table.js
and i want OUTPUT like that(wanna remove .js from )
pieChart
stackedColumnChart
table
var array = ['pieChart.js', 'stackedColumnChart.js', 'table.js'];
var modifiedArray = array.map(function(el) {
return el.replace('.js', '');
});
console.log(modifiedArray);
If input is a multi-line string:
var input = "pieChart.js\n" +
"stackedColumnChart.js\n" +
"table.js";
var output = input.replace(/\.js$/mg, '');
If it's an array:
var input = ["pieChart.js","stackedColumnChart.js","table.js"];
var output = $.map(input, function(el){
return el.replace(/\.js$/, '');
});
You can loop through the strings and take substring of those strings.
In this case :
var array = ['pieChart.js', 'stackedColumnChart.js', 'table.js'];
for (item in array){
newItem = item.substr(0, item.length-3);
console.log(newItem);
}
You just substring the characters except the last 3
var dotJS = "pieChart.js";
var withoutJS = dotJS.substr(0,dotJS.length-3);
alert (withoutJS);
Now you have a string minus those last three characters.
(pffft... Wow, I'm late with my answer here.)

trim a string path using javascript

I have the following string:
var fileName = $(this).val();
this will give me a result:
C:\fakepath\audio_recording_47.wav
what I want is to obtain : audio_recording_47.wav
so, I need to trim it but I don't know how using javascript
please help
filename.split('\\').reverse()[0];
This will split the path by slashes, to obtain each part. Then to keep it simple, i reverse the array, so the last part that you need is now the first; and get the first part.
Or, even more simply: filename.split('\\').pop(), which will get the last item from the array.
You could write a little function to return the base name of the path:
function basename(fn) {
var x = fn.lastIndexOf("\\");
if (x >= 0) return fn.substr(x + 1);
return fn;
}
var filename = basename($(this).val());
You can do like this:
var fileName = $(this).val();
var path = fileName.split('\\');
var lastValue = path[path.length-1];
console.log(lastValue);//audio_recording_47.wav
Or, the shorter way you can do like this:
var fileName = $(this).val();
var path = fileName.split('\\').slice(-1);//audio_recording_47.wav
This should do it:
var trimmedFileName = fileName.match(/[^\\]*$/);
It matches everything that isn't a \ until the end of the string.
You could use a regular expression, like this:
var fileName = this.value.replace(/(?:[^\\\/]*[\\\/])*/, '');
Also, there is no need to use that snippet of jQuery, as this.value is both faster and simpler.

Categories