Replace specific words amongst page content with value javascript - javascript

I'm trying to replace the word hello anywhere on the page with the word hi using Javascript. I created the script below however it isn't working how anticipated, is there something that I can do to achieve the outcome desired.
function(data) {
var newdata = data.replace("hello", "hi");
}
Jsfiddle

This will work, although might be overkill using regular expressions:
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, "hi")
Jsfiddle

In your example, you are only replacing the first occurence.
Below the JavaScript documentation about replace:
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
You have to use the global modifier as below
function(data) {
var newdata = data.replace(/hello/g,"hi");
}

Related

How do I create a custom javascript variable that selects part of an already existing javascript variable?

I am trying to create a custom javascript variable in GTM that returns part of a javascript variable that already exists.
Variable that already exists: window.ShopifyAnalytics.meta.product.variants.0.name
returns this: "Bamboo Basic String - Schwarz - S"
However I want to code a custom javascript variable to just return the Schwarz part, is this possible? If so what is the code that I would need?
Please can someone let me know what code to put into GTM to create this variable?
TIA
If all names are pretty much the same you could use split to get that part of string and then remove whitespaces. It would look like this:
window.ShopifyAnalytics.meta.product.variants.0.name.split('-')[1].replace(/
/g,'');
If the already existing variable is always structured the same way you could do something like this:
let variable = window.ShopifyAnalytics.meta.product.variants.0.name.split('-')
Then by calling varaible[1] you get the 'Schwartz' part of the variable.
If you want a return value you can use a function like the following and call it wherever you want.
Simply make sure to pass the correct argument content
// Declaring a function getColor that returns the second element in the list,
// trimmed (without spaces before and after)
const getColor = (content) => {
return content.split('-')[1].trim();
}
const test = "Bamboo Basic String - Schwarz - S";
console.log(getColor(test));
//console.log(getColor(window.ShopifyAnalytics.meta.product.variants.0.name));
You could split the string on the hypens (-) like this:
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
const part = productName.split(' - ')[1];
Assuming you have a consistent format, and you always want the second part after that hyphen.
split will separate parts of a string into an array where it finds a match for the argument. The first index [0] will be the product name, the second [1] will be the part you're looking for.
This could cause issues if you have a product name with a - in it too though so use with care!
If it needs to be an anonymous function for GTM, you could try the following (though I'm not a GTM expert):
function () {
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
return productName.split(' - ')[1] || 'Unknown';
}

Make text content between specified HTML tags toUpperCase in React-Native

I want to make to uppercase the contents of specific HTML tags with plain JavaScript in a React-Native application.
Note: This is a React-Native application. There is no JS document, available, nor jQuery. Likewise, CSS text-transform: uppercase cannot be used because it will not be displayed in a web browser.
Let's say, there is the following HTML text:
<p>This is an <mytag>simple Example</mytag></p>
The content of the Tag <mytag> shall be transformed to uppercase:
<p>This is an <mytag>SIMPLE EXAMPLE</mytag></p>
I tried this code:
let regEx = storyText.match(/<mytag>(.*?)<\/mytag>/g)
if(regEx) storyText = regEx.map(function(val){
return val.toUpperCase();
});
But the map() function returns only the matched content instead of the whole string variable with the transformed part of <mytag>.
Also, the match() method will return null, if the tag wasn't found. So a fluent programming style like storyText.match().doSomething isn't possible.
Since there are more tags to transform, an approach where I can pass variables to the regex-pattern would be appreciated.
Any hints to solve this?
(This code is used in a React-Native-App with the react-native-html-view Plugin which doesn't support text-transform out of the box.)
Since it seems that document and DOM manipulation (e.g., i.e., through jQuery and native JS document functions) are off limits, I guess you do have to use regex.
Then why not just create a function that does a job like the above: looping through each tag and replacing it via regex?
var storyText = "your HTML in a string";
function tagsToUppercase(tags) {
for(tag in tags) {
let regex = new RegExp("(<" + tags[tag] + ">)([^<]+)(<\/" + tags[tag] + ">)", "g");
storyText = storyText.replace(regex, function(match, g1, g2, g3) {
return g1 + g2.toUpperCase() + g3;
});
}
}
// uppercase all <div>, <p>, <span> for example
tagsToUppercase(["div", "p", "span"]);
See it working on JSFiddle.
Also, although it probably doesn't apply to this case, (#Bergi urged me to remind you to) try to avoid using regular expressions to manipulate the DOM.
Edit, Updated
The content of the Tag < mytag > shall be transformed to uppercase:
<p>This is an <mytag>SIMPLE EXAMPLE</mytag></p>
You can use String.prototype.replace() with RegExp /(<mytag>)(.*?)(<\/mytag>)/g to create three capture groups, call .toUpperCase() on second capture group
let storyText = "<p>This is an <mytag>simple Example</mytag></p>";
let regEx = storyText.replace(/(<mytag>)(.*?)(<\/mytag>)/g
, function(val, p1, p2, p3) {
return p1 + p2.toUpperCase() + p3
});
console.log(regEx);
In general you shouldn't be parsing html with javascript. With that in mind, if this is what you truly need to do, then try something like this:
let story = '<p>smallcaps</p><h1>heading</h1><div>div</div><p>stuff</p>';
console.log( story.replace(/<(p|span|div)>([^<]*)<\/(p|span|div)>/ig,
(fullmatch, startag,content,endtag) => `<${startag}>${content.toUpperCase()}</${endtag}>` )
)
Consider the cases where you might have nested values, p inside a div, or an a or strong or em inside your p. For those cases this doesn't work.
Why not this way ?
$("mytag").text($("mytag").text().toUpperCase())
https://jsfiddle.net/gub61haL/

Escape metacharacters and using it as string variable for selector

eg.
I have var myid="abc xyz"
then I escape metachars using function and get var x = "#"+escapechars(myid);
which evaluate to #abc\\xyz
Now when I try to do $(x) it doesn't get any element
but when I type $("#abc\\xyz") in watch it gets the element.
I am attaching a screenshot for same scenario.
Problem is : I want to select the element using variable
Thank you.
Here is the jsfiddle for my scenario.
http://jsfiddle.net/9hq4nzvx/3/
This >http://jsfiddle.net/9hq4nzvx/5/ solves the issue.
When we are using string variable that time we only need a single backslash instead of 2.
function escapechars now returns : "#abc\ xyz" which gets the element as needed.
var selection ="abc xyz";//this can be anything else comes from an array.
var x = "#"+escapeStr(selection); //"#abc\\\\\ xyz";
$(x).html("<h1>Hii</h1>");//why don't I get element here?
console.log(x);
alert(x);
$("#abc\\ xyz").append("<h2>bye</h2>");
function escapeStr(str) {//escape special chars from selectors
if (str)
return str.replace(/([ !"#$%&'()*+,.\/:;<=>?#[\\\]^`{|}~])/g, '\\$1');
return str;
}

using javascript to replace onpage javascript

I'm fairly new to javascript so please go easy on me,
I have this code on a webpage:
<script type="text/javascript"> bb1 = "oldcode"; bb2 = "morecodehgere"; bb3 = 160000;</script>
I want to replace 1% of all page loads oldcode to newcode
There are multiple instances of this code on the same page and I want to replace them all.
window.onload = replaceScript;
function replaceScript() {
var randomNumber = Math.floor(Math.random()*101);
var toReplace = 'oldcode';
var replaceWith ='newcode';
if randomNumber == 1 {
document.body.innerHTML = document.body.innerHTML.replace(/toReplace/g, replaceWith);
}
}
This is the current code I've got but it doesn't work.
Is javascript the bast way to achieve what I'm looking to do? If so whats the best way to do this?
The regular expression literal:
/toReplace/g
will create a regular expression object that matches the string "toReplace". If you want to create a regular expression to match the (string) value of the variable toReplace, you must use the RegExp constructor:
var re = new RegExp(toReplace, 'g');
It is not a good idea to replace the innerHTML of the body with a copy of itself. The innerHTML property doesn't necessarily reflect all the nuances of the DOM and will not include things like dynamically added listeners. It also varies from browser to browser.
Using a regular expression to replace parts of innerHTML is almost certain to produce unpredictable results, it may work well on trivial pages but will not be reliable on complex pages.

Replace Word Within Word - Javascript

I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.

Categories

Resources