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');
});
Related
trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.
I want to get a portion of a string via .substring(indexStart, indexEnd) then replace the same portion in the original string.
var portion = "my new house".substring(3, 6),
portion = "old";
// what's next?
You could take the surrounding substrings and concatenate:
var str = "my new house";
str = str.slice(0, 3) + "old" + str.slice(6);
console.log(str); // "my old house"
Of course, this is assuming you want to replace parts of the string marked off by certain indeces. If you just want to replace a word, you would use:
str = str.replace(/new/g, 'old');
(Omit the global flag to only replace the first occurrence.)
You just need to call 'replace' on the original string to find the substring you gathered and replace it with the new desired string.
var oldString = "my new house my new house";
var subStr = oldString.substring(indexStart, indexEnd);
var newValue = "old";
var newString = oldString.replace(subStr, newValue);
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;
}
How do I truncate a string after or before a pattern?
Say if I have a string "abcdef" I need to truncate everything after "abc" so the output will be:
def
and if i say truncate before "def" the output should be:
abc
Below is the code that I tried
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc"), str1.length);
console.log(str2);
I didn't get the output.
I'm stuck here any help will be much appreciated.
You need to pass length of "abc" as the 2nd argument in substr method
var str1 = "abcdefgh";
var pattern = "abc";
var str2 = str1.substr(str1.indexOf(pattern), pattern.length); <-- check this line
console.log(str2);
However above code might return unexpected results for patterns which are not present in the string.
var str1 = "abcdefgh";
var pattern = "bcd";
var str2 = "";
if(str1.indexOf(pattern)>=0) //if a pattern is not present in the source string indexOf method returns -1
{
//to truncate everything before the pattern
//outputs "efgh"
str2 = str1.substr(str1.indexOf(pattern)+pattern.length, str1.length);
console.log("str2: "+str2);
// if you want to truncate everything after the pattern & pattern itself
//outputs "a"
str3 = str1.substr(0, str1.indexOf(pattern));
console.log("str3: "+str3);
}
var str = "sometextabcdefine";
var pattern = "abc";
var truncateBefore = function (str, pattern) {
return str.slice(str.indexOf(pattern) + pattern.length);
};
var truncateAfter = function (str, pattern) {
return str.slice(0, str.indexOf(pattern));
}
console.log(truncateBefore(str, pattern)); // "define"
console.log(truncateAfter(str, pattern)); // "sometext"
Please see the below code:
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc")+3, str1.length);
alert(str2);
You were correct but one thing you missed is doing +3 in the indexOf.
the indexOf("abc") would return 0 which in turn will give you thw whole string again.
Or check out this fiddle link:
Working Fiddle
How about something like this:
function truncateAfter(original, pattern) {
return original.substring(0, original.indexOf(pattern) + pattern.length);
}
What this does is find the first index of the pattern you're looking for, and return a substring of the original string that starts at the beginning and ends after the first instance of the pattern.
Example Usage:
truncateAfter('dabcdefghi', 'abc');
>> 'dabc'
If instead you want to truncate the output before and after the pattern you're looking for, would just checking if the pattern is in the string and then using the pattern as the output be what you're looking for?
function truncate(original, pattern) {
if (original.indexOf(pattern) != -1) {
return pattern;
}
}
Example Usage:
truncate('dabcdefghi', 'abc');
>> 'abc'
How can i do to search if a Javascript String contains the following pattern :
"#aRandomString.temp"
I would like to know if the String contains # character and then any String and then ".temp" string.
Thanks
This one liner should do the job using regex#test(Strng):
var s = 'foo bar #aRandomString.temp baz';
found = /#.*?\.temp/i.test(s); // true
Use indexOf to find a string within a string.
var string = "#aRandomString.temp";
var apos = string.indexOf("#");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp #"
if (apos !== -1 && dtemp !== -1) {
var aRandomString = string.substr(apos + 1, dtemp - apos);
console.log(aRandomString); // "aRandomString"
}
You can try this
var str = "#something.temp";
if (str.match("^#") && str.match(".temp$")) {
}
demo
You can use the match function.
match expects the regular expression.
function myFunction()
{
var str="#someting.temp";
var n=str.test(/#[a-zA-Z]+\.temp/g);
}
Here is a demo: http://jsbin.com/IBACAB/1