How to remove a word from ID in jquery? - javascript

How can I remove a single word from an ID using Jquery?
For example, I have a div with ID page_getstarted and I want to get that ID in jquery and use it for something else but I don't want to use that whole ID I just want to use get_started.
Is there a way to get an id and trim it?

Since you mentioned that you already know how to get the id attribute, I'll suggest you to create a function to check a specified string param (in your case you need to pass the id attribute), check if it contains the word you want to remove, if it does you'll remove and return the modified string which you can store in a variable to reuse. For instance like so:
const removeStrFromId = (strId, searchQuery) => (strId.includes(searchQuery) ? strId.replace(searchQuery, "") : "");
const newModifiedStr = removeStrFromId("page_getstarted", "page_");
console.log(newModifiedStr); // outputs the string "getstarted"
You can reuse this function to manipulated other strings in the future if needed...

you can fetch id as
var container = $('#page_getstarted');
idText = container.attr('id'));
then use javascript to manipulate your string use split/replace method.
var idParts= idText.split("_");
var myId = idParts[1];

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

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.

How do I retrieve nodes with one or another value with XPATH

I have a javascript function that needs to retrieve certain nodes through xpath using document.evaluate, till now I am using something like
.//span[contains(#title, 'alerting')] | .//span[contains(#title, 'caution')]
But it turn in a very long string when values to match are more. I cannot use [#title = word], because I need to retrieve the elements whose atributes contains some string. I have tried things like
.//span[contains(#title, ('alerting'|'caution'))]
But it does not retrieve anything.
Can you give me an idea to shorten the first sintax?
Why not just create a function that creates the string and build the expression programmatically, and not worry about it? Roughly:
function spanContains(s) {
return ".//span[contains(#title, '" + s + "')]";
}
var contains = [spanContains('word1'), spanContains('word2')].join("|");
You could also try using matches instead of contains, although I'm not sure what the JavaScript syntax for that would be, or if it's supported.
XPath should be this way:-
.//span[contains(#title, 'alerting') or contains(#title, 'caution')]
.//span[contains(#title, ('alerting'|'caution'))]
This is invalid XPath -- the union operator | can only have arguments that are node-sets -- not strings.
Use:
.//span[#title
[contains(.,'alerting')
or
contains(.,'caution')
]
]
Instead of using document.evaluate(), you could use jquery in which case you could do:
$('span').filter(function() {
var title = $(this).attr('title');
return title != undefined && title.search(/(alerting|caution)/) != -1;
});

Get values from hash in URL using jquery

If I re-rite the URL using :
var id = 150
window.location.hash = "id="+id;
how to get the value of id using jQuery ?
No jQuery needed..
var id = /^#?id=(.+)/.exec(location.hash);
id = id ? id[1] : '';
// OR
var id = location.hash.substr(4); // (when hash can only be #id=..)
// This also selects 123 in #no=123 (!)
+1 for Rob W's answer not to use jQuery for this. But there're two things, i'd like to point out.
1.) Executing a regular expression, plus using a tertiary operator is "overload", too. ;-)
2.) You should consider that some browers return the hash symbol, and some don't!
To avoid to truncate the actual value part, I'd say it's safer to use replace(), instead of substr():
var id = location.hash.replace('id=', '').replace('#', '');
UPDATE:
I think split() is an even better solution:
var id = location.hash.split('id=')[1];
Just one (native) function call, which also "checks" if the request URL actually contains a hash that contains the string "id=idString".
If it does, the value of var id is "idString". If not, value of var id is undefined.

How to get whats inside a variable ID or Class

Say I have this:
var name = $('#contactName');
Is there a way to get just the contactName out of that variable?
Edit: The variable is already set and the value of it is $('#contactName').
What I want to do is retrieve the text from that variable, not create multiple variables. I could easily duplicate variables and just do var nameID = 'contactName' but I am hoping theres an alternative.
You can use the selector property:
var name = $('#contactName');
alert(name.selector); // alerts #contactName
However, you'd have to strip the #, so something like:
s.selector.replace('#','')
Obviously, this would only work for ID-based or tag-based selectors. Class-based selectors would need the . removing.
Try
var name = $('#contactName').attr('id');
All jQuery objects have a selector property that will return the selector they were created with, so your name object would return #contactName. You could then strip off the hash sign.
The title and body of your question seem at odds.
To answer the title:
If the jQuery object was created with a selector, then name.selector should do the trick.
To answer the body:
name.attr('id')
Don't you just use
var name= $("#contactName").val()
??

Categories

Resources