I've a email as string (let's say "testdrive#gmail.com") and I want to check if email contains character "test" then capitalize that
(ex. testdrive#gmail.com = "TESTdrive#gmail.com", drivetest#gmail.com= "driveTEST#gmail.com"...).
How do I get this in JavaScript?
Thanks!
You can do it with the String.prototype.replace and String.prototype.toUpperCase functions like this:
var original = "testdrive#gmail.com"
var replaceTerm = 'test';
var modified = original.replace(replaceTerm, replaceTerm.toUpperCase());
console.log(modified); //logs TESTdrive#gmail.com
Javascript's replace method is the easiest way to find and replace an exact keyword. The first parameter is the string you are searching for. The second is what you want to replace that string with.
var str = "testdrive#gmail.com";
var x = str.replace('test', 'TEST');
console.log(x); //TESTdrive#gmail.com
function capitalizer() {
var mail = "drivetest#gmail.com";
var srchStr = "test";
var n = mail.search(srchStr);
var capitalized = mail.replace(srchStr,mail.substr(n, srchStr.length).toUpperCase());
document.getElementById("demo").innerHTML = capitalized;
}
Related
I have this string:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
I need to do a method that erases a certain word with regular expressions.
Example:
var word = "familyId";
var newChain = deleteParam(chain, word);
console.log(newChain);
Result = "providerId=12$brandId=1122112$officeId=21&";
Delete : familyId=123&
I tried to do the method in the following way, but it does not work:
function deleteParam(chain, word) {
var exp = new RegExp(param, "=[0-9]&");
var str = chain.replace(exp, ""); // Delete
return str
}
Please, I need your help, I can not make this method work, because I do not understand well how to build regular expressions.
Excuse me all, English is not my native language
thank you very much to all.
You can use something like this new RegExp(param + "=\[^&]+")
Here is an example:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
var toRemove = "familyId";
var pattern = new RegExp(toRemove + "=[^&]*&");
var newChain = chain.replace(pattern, "");
console.log(newChain);
If you're looking to process a GET request's search parameters is better to use a pattern like this (&|\?)*parameterName=[^&]*
I have a bunch of strings in the format 'TYPE_1_VARIABLE_NAME'.
The goal is to get 3 variables in the form of:
varType = 'TYPE',
varNumber = '1',
varName = 'VARIABLE_NAME'
What's the most efficient way of achieving this?
I know I can use:
var firstUnderscore = str.indexOf('_')
varType = str.slice(0, firstUnderscore))
varNumber = str.slice(firstUnderscore+1,firstUnderscore+2)
varName = str.slice(firstUnderscore+3)
but this feels like a poor way of doing it. Is there a better way? RegEx?
Or should I just rename the variable to 'TYPE_1_variableName' and do a:
varArray = str.split('_')
and then get them with:
varType = varArray[0],
varNumber = varArray[1],
varName = varArray[2]
Any help appreciated. jQuery also ok.
Regex solution
Given that the first and second underscores are the delimiters, this regex approach will extract the parts (allowing underscores in the last part):
//input data
var string = 'TYPE_1_VARIABLE_NAME';
//extract parts using .match()
var parts = string.match(/([^_]+)_([^_]+)_([^$]+)/);
//indexes 1 through 3 contains the parts
var varType = parts[1];
var varNumber = parts[2];
var varName = parts[3];
Given that the first variable consists of characters and the second of digits, this more specific regex could be used instead:
var parts = string.match(/(\w+)_(\d)_(.+)/);
Non-regex solution
Using .split('_'), you could do this:
//input data
var string = 'TYPE_1_VARIABLE_NAME';
//extract parts using .split()
var parts = string.split('_');
//indexes 0 and 1 contain the first parts
//the rest of the parts array contains the last part
var varType = parts[0];
var varNumber = parts[1];
var varName = parts.slice(2).join('_');
In matters of efficiency, both approaches contain about the same amount of code.
You could use regex and split
var string='TYPE_1_VARIABLE_NAME';
var div=string.split(/^([A-Z]+)_(\d+)_(\w+)$/);
console.log('type:'+div[1]);
console.log('num:'+div[2]);
console.log('name:'+div[3]);
Here's an answer I found here:
var array = str.split('_'),
type = array[0], number = array[1], name = array[2];
ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now:
var [type, number, name] = str.split('_');
You can check browser support using Kangax's compatibility table.
Here's a sample Fiddle
How do i replace the text with each method?
Is it right? it doesnt replace / find the text correctly
$(function(){
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var cur_style = $('#obj').attr('class');
var new_style;
$(style_find).each(function(i,cl){
new_style = cur_style.replace(cl,'new-class');
// it doesnt replace the whole word
});
})
String.prototype.replace() behaves differently depending upon the type of it's first parameter. Consider this code:
var example = "str str str str";
example = example.replace("str", "bob");
console.log(example === "bob str str str"); // === true?
I gave replace() a string for it's first parameter. When you do so, it only replaces the first occurrence of the substring.
When you call replace() with a RegExp you get something that returns all matches replaced
var example = "str str str str";
example = example.replace(/str/g, "bob");
console.log(example === "bob bob bob bob"); // === true
What we need is a regexp that matches everything you want to replace.
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var regexp = (function() {
var inner = "";
style_find.forEach(function(el) {
inner = inner + el + "|";
});
return new RegExp(inner, "g");
}());
With regexp I can modify your code to:
$(function(){
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var cur_style = $('#obj').attr('class');
var new_style = cur_style.replace(regexp, 'new-class');
});
I have a RegExp that I would like to make dynamic and create in a string. I want to change this:
var result:Object = value.match(/John\/(.*?) /);
to this:
var firstName:String = "John";
var result:Object = value.match(firstName + "\/(.*?) "); // this doesn't work
I'm using ActionScript but I think what would work in JavaScript would work as well here.
In Javascript you can create a new instance of the RegExp class:
var firstName:String = "John";
var result:Object = value.match(new RegExp(firstName + "\/(.*?) "));
When you use value.match(firstName + "\/(.*?) "); the first parameter to the match function is a string, but it should be a regular expression object.
I want to extract the date and the username from string using .split() in this particular string:
var str ='XxSPMxX on 08/30/2012';
I want XxSPMxX in one variable and 08/30/2012 in the other.
Using just split:
var x = str.split('</a> on ');
var name = x[0].split('>')[1];
var date = x[1];
Demo: http://jsfiddle.net/Guffa/YUaAT/
I don't think split is the right tool for this job. Try this regex:
var str ='XxSPMxX on 08/30/2012',
name = str.match(/[^><]+(?=<)/)[0],
date = str.match(/\d{2}\/\d{2}\/\d{4}/)[0];
Here's the fiddle: http://jsfiddle.net/5ve7Y/
Another way would be to match using a regular expression, build up a small array to get the parts of the anchor, and then use substring to grab the date.
var str = 'XxSPMxX on 08/30/2012';
var matches = [];
str.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
matches.push(Array.prototype.slice.call(arguments, 1, 4))
});
var anchorText = matches[0][2];
var theDate = str.substring(str.length - 10, str.length);
console.log(anchorText, theDate);
working example here: http://jsfiddle.net/dkA6D/