Javascript or jQuery replace text - javascript

I need to replace some text that is on the page within the body tag. I am using javascript but have jquery available if needed. I basically need to replace test® (test with the registered trademark) with TEST® or tests® with TESTS® and it could even be test with TEST® or tests with TESTS®. I am able to uppercase them but its not liking to work for me with the ® sign, it wants to put duplicates on ones that already have it. Basically anything on the page that has the word test or tests should be TEST® or TESTS® if it is plural. Any help is appreciated.
EDIT:
So now I have this:
var html = $('body').html();
var html = html.replace(/realtor(s)?(®)?/gi, function(m, s1, s2){
var s = s1?s1.toUpperCase():"";
var reg = s2?s2:'®';
return "REALTOR"+s+reg;
});
$('body').html(html);
Its working well other than it is duplicating the ® on the ones that already had them any ideas on how not to?

As others have already said, you will not be able to match the ®, you need to match on
\u00ae.
The code you provided needs to be changed to:
var html = $('body').html();
var html = html.replace(/realtor(s)?(\u00ae)?/gi, function(m, s1, s2){
var s = s1?s1.toUpperCase():"";
var reg = s2?s2:'®';
return "REALTOR"+s+reg;
});
$('body').html(html);

To expand on jAndy's answer, try this:
$("div, p, span").each(function(){
o = $(this);
o.html( o.text().replace(/test(|s)\u00ae/gi, function($1){
return($1.toUpperCase());
}));
});
Using the code you provided, try this:
$(document).ready(function(){
$('body').html( $('body').html().replace(/realtor(|s)\u00ae/gi, function($1){
return($1.toUpperCase() );
}));
})

Instead of creating something from scratch try using an alternate library. I develop with PHP so using a library that has identical methods in JavaScript is a life saver.
PHP.JS Library
var newReplaced = $P.str_replace("find","replace",varSearch);

The tricky part here is to match the ®, which is a Unicode character, I guess...
Have you tried the obvious?
var newStr = str.replace(/test(s)?®?/gi, function(m, s1){
var s = s1?s1.toUpperCase():"";
return "TEST"+s+"®";
});
If the problem is that ® does not match, try with its unicode character number:
/test(s)?\u00ae/
Sorry if the rest does not work, I assume your replacement already works and you just have to also match the ® so that it does not get duplicated.

Related

Javascript - regex replace string [duplicate]

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

Can I pass multiple args (patterns) for Javascript's replace()? If not, any good alternative?

I'm taking the following ex URL https://support.dev.mysite.com/batch/ and removing everything, but the environment (eg dev). The below code works fine.
var env = endPoint.replace("https://support.", "\n");
var envClean = env.replace(".mysite.com/batch/", "\n");
I don't like repeating myself. I would like to look for both patterns in the string and remove them all at once. MDN has a good breakdown of replace() here - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace but it doesn't mention anything about multiple arguments.
I've tried this:
var env = endPoint.replace("https://support." && ".mysite.com/batch/", "\n");
but it just parses the second arg and disregards the first.
Does anyone have a cleaner way of doing this? I'm assuming I can search for multiple patterns via REGEX, any REGEX masters out there care to help?
Cheers.
You can use regular expressions for this:
var environment = 'https://support.dev.mysite.com/batch/'
.replace(/^https:\/\/support\.|\.mysite\.com\/batch\/$/g, '');
You could chain your method:
var envClean = endPoint.replace("https://support.", "\n").replace(".mysite.com/batch/", "\n");
Or you could use regex:
var envClean = endPoint.replace(/https:\/\/support\.|\.mysite\.com\/batch\//, "\n");
And there is another solution to get dev:
var envClean = endPoint.match(/^https:\/\/support\.([^.]*)\.mysite\.com\/batch\/$/)[1];
For this specific URL pattern, why not make it really simple and use .split():
var url = 'https://support.dev.mysite.com/batch/';
var name = url.split('.')[1];
If I were using a regular expression, I would probably do it this way:
var match = url.match( /support\.(.*)\.mysite.com/ );
var name = match && match[1];
Note that you don't have to worry about the entire URL this way, only enough to do the match.
If you know that the URL will match, you can simplify that to:
var name = url.match( /support\.(.*)\.mysite.com/ )[1];

Highlighting with jquery or JavaScript?

I am newbie in programming and I have a question that has been asked many times in the past. I need to implement highlight in some fashion. I have seen a jquery plugin ( SearchHighlight). Jquery is using selectors. To be honest I don't whant to use them. What I need is to "feed" the plugin the string to be highlighted and the string that holds the search words via variables ex.
var searchterms = 'lolo loli let';
var searchstring = ' Lolo loves loli and .... Blah, blah';
var highlightedstring = '';
// SearchHighlight plugin
highlightedstring return;
If the above is not possible is there a way in pure JavaScript to do substring highlighting?
With respect,
Tom
Greece
The concept around highlighting is to grab the html from the container where you're searching an wrap the word(s) found with tags that you can style. Simple example with just one word, but this could be extended with an array of words.
function highlight(word, content) {
var html = $(content).html();
var re = new RegExp(word, 'gi');
$(content).html(html.replace(re, '<code>$&</code>'));
}
highlight('pleasure', '#content');
Demo: http://jsfiddle.net/elclanrs/hdYmb/

JavaScript, Regex and null result

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.

Using javascript regex to translate a html

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
.

Categories