find and replace strings in jquery - javascript

$('img').click(function(){
var add_to_list = $(this);
// database query for element
});
Currently add_to_list is getting the value 'images/image.jpg'. I want to replace the 'image/' to nothing so I only get the name of the picture (with or without the extension). How can I do this? I couldn't find anything. Also please provide me with further reading on string manipulation please.

Have you tried javascript replace function ?
You should modify your code to something like this:
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('images/', '');
// database query for element
});

use
add_to_list.substring(7);
This will get you the string after the 7th character. If there might be longer paths, you can split() into an array and get the last part of the path using pop().
add_to_list.split("/").pop();
substring
split
pop
This tutorial explains many of the string manipulation methods seen in the answers here.

$('img').click(function(){
var add_to_list = $(this).attr('src').replace('image/', '');
// database query for element
});

var pieces = add_to_list.split('/');
var filename = pieces[pieces.length-1];

Related

Get data from URL address

I have a website like below:
localhost:3000/D129/1
D129 is a document name which changes and 1 is section within a document.
Those two values change depends on what user selects.
How do I just extract D129 part from the URL using javascript?
window.location.pathname.match(/\/([a-zA-Z\d]*)/)[1]
^ that should get you the 1st string after the slash
var path = "localhost:3000/D129/1";
alert(path.match(/\/([a-zA-Z\d]*)/)[1])
You can use .split() and [1]:
a = "localhost:3000/D129/1";
a = a.split("/");
alert(a[1]);
This works if your URLs always have the same format. Better to use RegEx. Wanted to answer in simple code. And if you have it with http:// or something, then:
a = "http://localhost:3000/D129/1";
a = a.split("/");
alert(a[3]);
ps: For the RegEx version, see Tuvia's answer.

How to open a link using jQuery which has an exact pattern at the end of it?

How to get a link using jQuery which has an exact pattern at the end of it? E, g, I have the following code:
return $(document).find("a[href='https://my_site.com/XX-' + /\d(?=\d{4})/g, "*"]");
So, the links could be: https://my_site.com/XX-1635, https://my_site.com/XX-7432, https://my_site.com/XX-6426 and so on.
In other words, it could be any 4 digits after the "XX-".
You can use filter() for this.
reg = /https:\/\/my_site.com\/XX-\d{4}$/g;
elements = $(document)
.find("a")
.filter(function(){
return reg.test(this.href);
});
return elements;
You can use filter() with attribute starts with selector.
var regex = /XX-\d{4}$/; // Exact four digits after XX-
var anchors = $(document.body)
.find('a[href^="https://my_site.com/XX-"]')
.filter(() => regex.test(this.href));
Where is the source of your data?
I suspect the data you are trying to read is encoded for safe transport. This is where the space is converted to to %20 for example.
If true, you need convert your source data using encodeURIComponent(), then apply your find.
This might work (though my usage of search is weak). I have not tested this code but should give you an idea on direction...
// Collate all href from the document and store in array links
var links=[];
$(document).find("a").each(
function()
{
links.push( encodeURIComponent( $(this).prop("href") ) );
});
// Loop thru array links, perform your search on each element,
// store result in array results
var results=[];
results=links.filter(function(item){
return item.search('/\d(?=\d{4})/g');
});
console.log( results );
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
No need for jQuery at all. Simply can be accomplished by pure JS in a single line. It's probably multiple times faster too.
var as = document.getElementsByTagName("a"),
ael = Array.prototype.filter.call(as, e => /XX-\d{4}$/g.test(e.href));

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 retrieve the last portion of the url using regex or jquery

I have a url
/stars/planets/usa/en/universe/planet_stars.html
I need to get the planets_stars.html. How do I get that last portion alone?
Neither jQuery nor regex necessary here:
url.split('/').pop();
Using pure javascript:
var url = "/stars/planets/usa/en/universe/planet_stars.html";
var page = url.substring(url.lastIndexOf("/")+1);
Edit: second parameter of substring method optional and not required in this case. So, I removed it.
or just JavaScript.
var parts = url.split('/');
var lastpart = parts[parts.length -1];
You can use pop() as jmar said too, just remember that removes it from the array when you do it, so you can't use the pop method twice on the same array and get the same value.

Trying to .replace() Without Success

I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));

Categories