Replace Word Within Word - Javascript - 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.

Related

how to make user input on screen to reflect on click event (js, html)

I am trying to write html and js codes to make user input to change according to which button user clicks. For example, user enters find/replace values respectively and when they hit the replace button, the user input they initially typed in will change. below is my code which is not working at all..
var str = document.getElementById('text').value;
var f = document.getElementById('find').value;
var r = document.getElementById('replace').value;
let rep = str.replace(f, r);
document.getElementById('text').innerHTML = rep;
//
<button onclick="funcname()">Replace</button><br>
You probably want to use replaceAll see docs
function replace() {
var f = document.getElementById('find').value;
var r = document.getElementById('replace').value
var text = document.getElementById('text');
text.textContent = text.textContent.replaceAll(f, r);
return null;
}
<div id="text">foo</div>
find <input id="find">
<div></>
replace <input id="replace">
<button onclick="replace()">Replace</button><br>
You need to create separate functions for what you are doing. Each button will call the functionality it desires.
Below, I have a paragraph with an id text. We can access it using document.getElementById or document.querySelector. Because it is a text element, we access the value using innerHTML.
For the input, we need an input element which has the id input. The value is accessed using value.
The replace is straight forward, set the innerHTML of the paragraph to the value of the input.
The find, not sure exactly what you wanted, but we can use string.includes() to find out whether the value in the input appears in the innerHTML of the paragraph.
Finally, there is find and replace, which can be solved with string.replace for replacing the first occurance, or you can change to string.replaceAll to replace all occurances.
const find = function() {
let str = document.getElementById('text').innerHTML;
let inp = document.getElementById('findInput').value;
let matched = str.includes(inp) ? 'was' : 'was not';
alert(`${inp} ${matched} found in the sentence.`);
};
const replace = function() {
document.getElementById('text').innerHTML = document.getElementById('replaceInput').value;
};
const findAndReplace = function() {
let str = document.getElementById('text').innerHTML;
let f = document.getElementById('findInput').value;
let r = document.getElementById('replaceInput').value;
document.getElementById('text').innerHTML = str.replace(f, r);
};
<p id="text">She sells sea shells on the sea shore.</p>
<label for="findInput">Find:</label> <input id="findInput" type="text"><br>
<label for="replaceInput">Repalce:</label> <input id="replaceInput" type="text"><br>
<button type="button" onclick="find()">Find</button><br>
<button type="button" onclick="replace()">Replace</button><br>
<button type="button" onclick="findAndReplace()">Find and Replace</button><br>
It looks like the issue is that replace() only replaces the first occurrence in the string, which is causing the issue.
There are two solutions for this issue, which are both very similar.
The first solution is to use String.replaceAll(). This is a new feature introduced in ES2021, which means that it doesn't support old browsers (e.g. Internet Explorer).
To use it, simply use the code below.
const rep = str.replaceAll(f, r); // This line has been modified
document.getElementById("text").innerHTML = rep;
It will use the new method (replaceAll()), which will replace all occurrences of f with r.
The second solution uses a similar, yet older function, called String.replace(). It is the same function that you are using, but we are going to use a different technique.
To replace all occurrences, you need to use RegExp to modify the behaviour.
Use the code below to replace all occurrences with replace().
const rep = str.replace(new RegExp(`${f}`, "g"), r); // This line has been modified
document.getElementById("text").innerHTML = rep;
This uses the new RegExp constructor to create a new RegExp instance. This is because we want to pass in a variable.
The second parameter is where the magic happens. The g means global. This makes the replace() method replace all of the occurrences.
In summary, both of these methods should work. Here are some circumstances of which one you should use.
Option 1: Use when targeting newer browsers, and are focused on readability.
Option 2: Use when targeting older browsers.
try NOT to use , instead of . because js isnt defining , and also if that doesnt work then try using const replacer = document.querySelector("#text");..replace only replaces the first selected word so you should try .replaceAll instead

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';
}

Replace specific words amongst page content with value 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");
}

JavaScript - Is it necessary to check for condtion first

I was wondering if it is necessary to check for the condition in this particular example.
The condition I'm talking about is if ( Id.indexOf("_") ).
It just checks to see if Id has an underscore and if so then set the variable to strip the underscore and replace with hyphen.
I know I can just use Id = Id.split("_").join("-"); without the if statement checking to see if the condition is true, but just wondering if in this case is it good practice to check for the condition first or not?
Which way would you do it? And explain why please.
Id = "My_ID";
var brand = "The Brand";
var b = brand.trim().toLowerCase();
var page = b.split(/\W+/g).join("-");
if ( Id.indexOf("_") ) {
Id = Id.split("_").join("-");
}
If there is no underscore your split() won't do anything, so no - there's no need for the if here. Go with something like that and you're fine:
Id = Id.split("_").join("-");
or
Id = Id.replace(/_/g, '-');
to avoid creating an array first.
This could answer your question:
console.log("mytext".split("_").join("-")); // mytext
console.log("my_text".split("_").join("-")); // my-text
furthermore condition in your code if (Id.indexOf("_")) does not work as you intended. You need to use if (Id.indexOf("_") > -1) or (~Id.indexOf("_"))

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.

Categories

Resources