I'm using Google map to get distance and time between two locations.
this works fine...
however, I would like to replace some texts/words that has been spit out on my page from google map api with my own texts/words.
for example: I would like to replace the about with ETA:
This is my javascript code to replace the word:
<script>
function myFunction() {
var str = document.getElementsByClassName("adp-summary").innerHTML;
var res = str.replace("about", "ETA: ");
document.getElementsByClassName("adp-summary").innerHTML = res;
}
</script>
but unfortunately this doesn't do anything and it doesn't replace the word about with ETA:.
Here is my entire code:
http://jsfiddle.net/dvw37ktu/1/
Could someone please advise on this issue?
Thanks in advance.
As mentioned in the comments, document.getElementsByClassName is returning a HTMLCollection that matches your selector, which is why you can't set the .innerHTML. This can be fixed by dealing with the collection, say, by looping over it:
var adpSummary = document.getElementsByClassName("adp-summary");
for (var i = 0; i < adpSummary.length; i++) {
// Do string replacement on adpSummary[i]
adpSummary[i].innerHTML = adpSummary[i].innerHTML.replace(new RegExp('about', 'gm'), 'ETA: ')
}
if only using native js, replace only replaces the first instance of the string.
you can either loop while index check:
while(str.indexOf("about") > -1)
{
//do replace here
}
or a better option is to use a regex.
see more here:
Why does javascript replace only first instance when using replace?
Related
Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.
I have written this regexp: <(a*)\b[^>]*>.*?</\1>
and is tested on this regexp testing site: http://gskinner.com/RegExr/?2tntr
The point of the regexp is to go through a sites HTML and find all of the links. It should then return these in an Array for me to manipulate.
On the regexp testing site it works perfectly, but when put in action with JavaScript on my site it returns null.
JavaScript looks like this:
var data = $('#mainDivOnMiddleOfPage').html();
var pattern = "<(a*).*href=.*>.*</a>";
var modi = "g";
var patt = new RegExp(pattern, modi);
var result = patt.exec(data);
jQuery gets the content of the page. This is tested and verified.
Question is, why does this return null in JavaScript but what it is supposed to return in the regexp tester?
All <a> links:
<a[^>]*?\bhref=['\"](.*?)['\"]
Absolute links only (starting with http):
<a[^>]*?\bhref=['\"](http.*?)['\"]
JavaScript code:
var html = '<a href="test.html">';
var m = html.match(/<a[^>]*?\bhref=['"](.*?)['"]/);
print (m[1]);
See and test the code here.
I use the following code to do the same thing and it works for me, try it out
var data = document.getElementById('mainDivOnMiddleOfPage').textContent;
var result = data.match(/<(a*).*href=.*>.*<\/a>/);
Going to go ahead and post this here, since I think it's what you want -- it is not a RegEx solution, however.
$(function(){
$.ajax({
url: "test.htm",
success: function(data){
var array_of_links = $.makeArray($("a",data));
// do your stuff here
}
});
});
I'm conscious an answer has been chosen. However it's worth mentioning that the current REGEX solutions match the tags but not the actual HREFs in isolation.
This is where JavaScript falls down, since its somewhat simplistic implementation of REGEX does not allow for the capturing of sub-groups when the global g flag is specified.
One way round this is to exploit the REGEX replacement callback. This will get just the link HREFs, not the tags.
var html = document.body.innerHTML,
links = [];
html.replace(/<a[^>]*?href=('|")(.*?)\1/gi, function($0, $1, $2) {
links.push($2);
});
//links is now an array of hrefs
It also uses a back-reference to close the href attribute, i.e. making sure both opening and closing quote are single or double, not mixed.
Sidenote: as others have mentioned, where possible, you'd want to DOM this rather than REGEX.
"The point of the regexp is to go through a sites HTML and find all of the links. It should then return these in an Array for me to manipulate."
I won't add another regex answer, but just want to point out that if you have hold of the document (not just the html) then it's easier to walk trhough the links collection. That contains all <a href="">'s but also all <area> elements:
for (var link, links = document.links, n = links.length, i=0; i<n; i++){
link = links[i];
switch (link.tagName){
case "A":
//do something with the link
break;
case "AREA":
//do something with the area.
break;
}
}
Your problem is that you are not compiling your regex:
patt.compile();
You have to call it before using with the exec() method.
I would like to build my own translation function in javascript.
I already have a function language.lookup(key) which translates a word or expression:
var frenchHello = language.lookup('hello') //'bonjour'
Now I would like to write a function which takes a html string and translates it with my lookup function. In the html string I will have a special syntax for example #[translationkey] that will point out that this word should be translated.
This is the result I want:
var html = '<div><span>#[hello]</span><span>#[sir]</span>'
language.translate(html) //'<div><span>bonjour</span><span>monsieur</span>
How would I write language.translate?
My idea is to filter out my special syntax with regex and then run language.lookup on each key. Maybe with string replace or something.
I suck when it comes to regex and I've only come up with a very incomplete example but I include it anyway so maybe someone get the idea of what I am trying to do. Then if there is a better but complete different solution that is more than welcome.
var value = "#[hello], nice to see you.";
lookup = function(word){
return "bonjour";
};
var res = new RegExp( "\\b(hello)\\b", "gi" ).exec(value)
for (var c1 = 0; c1 < res.length; c1++){
value = value.replace(res[c1], lookup(res[c1]))
}
alert(value) //#[bonjour], nice to see you.
The regex should of course not filter out the word hello but the syntax and then collect the key by grouping or similar.
Can anyone help?
Just use String.replace method's ability to call function specified as second argument to generate replacement text and make a global replace using regexp matching your syntax:
var value = "#[hello], #[sir], nice to see you.";
lookup = function(full_match, word){
if(word == 'hello')
return "bonjour";
if(word == 'sir')
return "monsieur"
};
console.log(value.replace(/#\[(.+?)\]/gi, lookup))
Result:
bonjour, monsieur, nice to see you.
Of course when your replacement list gets bigger, you'd better use lookup object instead of series of ifs in lookup function, but you can really do whatever you want there.
You can try this to find all occurrences:
var re = new RegExp('#\\[([^\\]]+?)\\]', 'gi'),
str = '#[value1] plain text #[value2]',
match;
while (match = re.exec(str)) {
console.log(match);
}
You could use something like:
#\\[[^\\]]*\\]
Which matches the hash followed by an opening square bracket followed by zero or more characters NOT including the closing square bracket, followed by a closed square bracket.
Alternatively, perhaps it would be better to handle the translation at the server side (maybe even through your template engine) and send back to your client the translated response. Otherwise, (depending on the specific problem you are dealing with of course), you might end up sending a lot of data to the browser which might make your application respond slowly.
EDIT:
Here is a working piece of code:
var q="This #[ANIMAL1] was eaten by that #[ANIMAL2]";
var u = {"#[ANIMAL1]":"Lion","#[ANIMAL2]":"Frog"};
function insertAnimal(aString, lookup){
var res = (new RegExp("#\\[[^\\]]*\\]", "gi"))
while (m = res.exec(aString)){
aString = aString.replace(m, lookup[m])
}
return aString;
}
function main(){
alert(insertAnimal(q,u));
}
You can call the "main()" from an HTML document's body onload event
I can compare your requirement to 'resolving template texts within content'. If it is feasible to use Jquery , you should try Handlebars.js
.
I have problem use array keyword and non-casesensitive search in innerHTML
I am trying write Greasemonkey JS which will remove tags which are containning keywords
function removebadcriptts() {
var scriptslinks = ['jumper.php','redirect.php'];
var theLinks = document.getElementsByTagName("script");
for (var i=0; i<scriptslinks.length; i++)
{
for (var j=0;j<theLinks.length;j++)
{
if (theLinks[i].innerHTML.search("/"+scriptslinks[i]+"/i/") !== -1)
/keyword/i = regular expression for non-case is not working
{
console.error("InnerHTML Keyword found ");
theLinks[j].parentNode.removeChild(theLinks[j]);
}
else
{
console.error("InnerHTML Keyword not found ");
}
}
}
}
Can anybody help howto remove and match this kind of scripts and remove from WEBpage also howto catch scripts which are injecting scripts into loaded webpage
When the Greasemonkey script is running, the scripts that are already on the page has already run. Removing them won't undo what these scripts did to the page.
Also the script that is inserted after the Greasemonkey script will not be catched, so this Greasemonkey probably will not work.
An alternative would be using NoScript add-on, because it is already designed to prevent scripts from running.
Edit: As the OP said that the primary problem is to make the search work, instead of storing patterns in a string inside an array, you can store patterns directly.
var scriptslinks = [/jumper\.php/i, /redirect\.php/i];
And when matching
if (theLinks[j].innerHTML.search(scriptslinks[i]) !== -1)
Note that a regex is passed directly to the search function. Also theLinks[i] should be theLinks[j].
Another solution: Use a single pattern.
if (theLinks[j].innerHTML.search(/jumper\.php|redirect\.php/i) !== -1)
That way you don't have to make 2 level for loops, and I think it will be faster, as the engine can search for 2 patterns at once.
search expects a RegExp object. So try this:
theLinks[i].innerHTML.search(new RegExp(scriptslinks[i], "i"))
Although you can pass a string too, it would be used create an RegExp object like new RegExp(string) but you can’t set the i modifier with that.
Furthermore, you should escape the special character of a regular expression like the .. You can use this method to do so:
RegExp.quote = function(str) {
return str.replace(/(?=[\\^$*+?.()|{}[\]])/g, "\\");
}
Do you mean
function removebadcriptts() {
var scriptslinks = ['jumper.php','redirect.php'];
var theLinks = document.getElementsByTagName("script");
for (var i=0; i<scriptslinks.length; i++)
{
for (var j=0;j<theLinks.length;j++)
{
if (theLinks[i].src.toLowerCase().indexOf(scriptslinks[i]) !== -1)
{
console.error("SRC Keyword found ");
theLinks[j].parentNode.removeChild(theLinks[j]);
}
else
{
console.error("SRC Keyword not found ");
}
}
}
}
Try using .Match, and i believe the regex would have to look like:
/scriptslink[i]/i
How can I use jquery on the client side to substring "nameGorge" and remove "name" so it outputs just "Gorge"?
var name = "nameGorge"; //output Gorge
No jQuery needed! Just use the substring method:
var gorge = name.substring(4);
Or if the text you want to remove isn't static:
var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');
Using .split(). (Second version uses .slice() and .join() on the Array.)
var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer
Using .replace().
var result = name.replace('name','');
Using .slice() on a String.
var result = name.slice( 4 );
Standard javascript will do that using the following syntax:
string.substring(from, to)
var name = "nameGorge";
var output = name.substring(4);
Read more here: http://www.w3schools.com/jsref/jsref_substring.asp
That's just plain JavaScript: see substring and substr.
You don't need jquery in order to do that.
var placeHolder="name";
var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);
var name = "nameGorge";
name.match(/[A-Z].*/)[0]
Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.
http://www.w3schools.com/jsref/jsref_substr.asp
The substr function will allow you to extract certain parts of the string.
Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well.
http://www.w3schools.com/jsref/jsref_IndexOf.asp
The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?
How about the following?
<script charset='utf-8' type='text/javascript'>
jQuery(function($) { var a=$; a.noConflict();
//assumming that you are using an input text
// element with the text "nameGorge"
var itext_target = a("input[type='text']:contains('nameGorge')");
//gives the second part of the split which is 'Gorge'
itext_target.html().split("nameGorge")[1];
...
});
</script>