Cut out, and replace a part of a string - javascript

There is a part in my string from, to which I would like to replace to an another string replace_string. My code should work, but what if there is an another part like the returned substring?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
For example:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
the str should be "abcezzxy"

What you want to do is simple! Cut out and replace the string. Here is the basic tool, you need scissor and glue! Oops I mean string.Split() and string.Replace().
How to use?
Well I am not sure if you want to use string.Split() but you have used string.Replace() so here goes.
String.Replace uses two parameters, like this ("one", "two") what you need to make sure is that you are not replacing a char with a string or a string with a char. They are used as:
var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3Schools");
Your code:
var from=10, to=17;
//...
var stringGot = str.replace(str.substring(from, to), replace_string);
What you should do will be to split the code first, and then replace the second a letter! As you want one in your example. Thats one way!
First, split the string! And then replaced the second a letter with z.
For String.Replace refer this: http://www.w3schools.com/jsref/jsref_replace.asp
For String.SubString: http://www.w3schools.com/jsref/jsref_substring.asp
For String.Split: http://www.w3schools.com/jsref/jsref_split.asp

Strings are immutable. This means they do not change after they are first instantiated. Every method to manipulate a string actually returns a new instance of a string. So you have to assign your result back to the variable like this:
str = str.replace(str.substring(from, to), replace_string);
Update: However, the more efficient way of doing this in the first place would be the following. it is also less prone to errors:
str = str.substring(0, from) + replace_string + str.substring(to);
See this fiddle: http://jsfiddle.net/cFtKL/
It runs both of the commands through a loop 100,000 times. The first takes about 75ms whereas the latter takes 20ms.

Related

Removing repeated string in javascript

I have problem one of my string has repeated url inside and I want to remove it. What's the best way to do it in javascript?
Following is example of string I referring to.
var str = "http://www.example.comhttp://www.example.com"
One solution is to reassign str to half of itself.
str = str.substring(str.length/2)
(This assumes the string will always follow the same format as the example you gave.)

Capitalize the first letter of each word

var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
var finalName = oldName;
// Your code goes here!
finalName = oldName.toLowerCase();
finalName = finalName.replace(finalName.charAt(0), finalName.charAt(0).toUpperCase());
for(i = 0; i < finalName.length; i++) {
if (finalName.charAt(i) === " ")
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
}
// Don't delete this line!
return finalName;
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
My code as is, returns 'Albert einstein'. I'm wondering where I've gone wrong?
If I add in
console.log(finalName.charAt(i+1));
AFTER the if statement, and comment out the rest, it prints 'e', so it recognizes charAt(i+1) like it should... I just cannot get it to capitalize that first letter of the 2nd word.
There are two problems with your code sample. I'll go through them one-by-one.
Strings are immutable
This doesn't work the way you think it does:
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
You need to change it to:
finalName = finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
In JavaScript, strings are immutable. This means that once a string is created, it can't be changed. That might sound strange since in your code, it seems like you are changing the string finalName throughout the loop with methods like replace().
But in reality, you aren't actually changing it! The replace() function takes an input string, does the replacement, and produces a new output string, since it isn't actually allowed to change the input string (immutability). So, tl;dr, if you don't capture the output of replace() by assigning it to a variable, the replaced string is lost.
Incidentally, it's okay to assign it back to the original variable name, which is why you can do finalName = finalName.replace(...).
Replace is greedy
The other problem you'll run into is when you use replace(), you'll be replacing all of the matching characters in the string, not just the ones at the position you are examining. This is because replace() is greedy - if you tell it to replace 'e' with 'E', it'll replace all of them!
What you need to do, essentially, is:
Find a space character (you've already done this)
Grab all of the string up to and including the space; this "side" of the string is good.
Convert the very next letter to uppercase, but only that letter.
Grab the rest of the string, past the letter you converted.
Put all three pieces together (beginning of string, capitalized letter, end of string).
The slice() method will do what you want:
if (finalName.charAt(i) === " ") {
// Get ONLY the letter after the space
var startLetter = finalName.slice(i+1, i+2);
// Concatenate the string up to the letter + the letter uppercased + the rest of the string
finalName = finalName.slice(0, i+1) + startLetter.toUpperCase() + finalName.slice(i+2);
}
Another option is regular expression (regex), which the other answers mentioned. This is probably a better option, since it's a lot cleaner. But, if you're learning programming for the first time, it's easier to understand this manual string work by writing the raw loops. Later you can mess with the efficient way to do it.
Working jsfiddle: http://jsfiddle.net/9dLw1Lfx/
Further reading:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
slice() method
You can simplify this down a lot if you pass a RegExp /pattern/flags and a function into str.replace instead of using substrings
function nameChanger(oldName) {
var lowerCase = oldName.toLowerCase(),
titleCase = lowerCase.replace(/\b./g, function ($0) {return $0.toUpperCase()});
return titleCase;
};
In this example I've applied the change to any character . after a word boundary \b, but you may want the more specific /(^| )./g
Another good answer to this question is to use RegEx to do this for you.
var re = /(\b[a-z](?!\s))/g;
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon";
s = s.replace(re, function(x){return x.toUpperCase();});
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"
The regular expression being used may need to be changed up slightly, but this should give you an idea of what you can do with regular expressions
Capitalize Letters with JavaScript
The problem is twofold:
1) You need to return a value for finalName.replace, as the method returns an element but doesn't alter the one on which it's predicated.
2) You're not iterating through the string values, so you're only changing the first word. Don't you want to change every word so it's in lower case capitalized?
This code would serve you better:
var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
// Your code goes here!
var finalName = [];
oldName.toLowerCase().split(" ").forEach(function(word) {
newWord = word.replace(word.charAt(0), word.charAt(0).toUpperCase());
finalName.push(newWord);
});
// Don't delete this line!
return finalName.join(" ");
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
if (finalName.charAt(i) === " ")
Shouldn't it be
if (finalName.charAt(i) == " ")
Doesn't === check if the object types are equal which should not be since one it a char and the other a string.

how to replace strings before another string

I have this string:
var str = "jquery12325365345423545423im-a-very-good-string";
What I would like to do, is removing the part 'jquery12325365345423545423' from the above string.
The output should be:
var str = 'im-a-very-good-string';
How can I remove that part of the string using php? Are there any functions in php to remove a specified part of a string?
sorry for not including the part i have done
I am looking for solution in js or jquery
so far i have tried
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("jquery12325365345423545423","");
but problem is numbers are randomly generated and changed every time.
so is there other ways to solve this using jquery or JS
The simplest solution is to do it with:
str = str.replace(/jquery\d+/, '').replace(' ', '');
You can use string replace.
var str = "jquery12325365345423545423im-a-very-good-string";
str.replace('jquery12325365345423545423','');
Then to removespaces you can add this.
str.replace(' ','');
I think it will be best to describe the methods usually used with this kind of problems and let you decide what to use (how the string changes is rather unclear).
METHOD 1: Regular expression
You can search for a regular expression and replace the part of the string that matches the regular expression. This can be achieved through the JavaScript Replace() method.
In your case you could use following Regular expression: /jquery\d+/g (all strings that begin with jquery and continue with numbers, f.e. jquery12325365345423545423 or jquery0)
As code:
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("/jquery\d+/g","");
See the jsFiddle example
METHOD 2: Substring
If your code will always have the same length and be at the same position, you should probably be using the JavaScript substring() method.
As code:
var str="jquery12325365345423545423im-a-very-good-string";
var code = str.substring(0,26);
str=str.substring(26);
See the jsFiddle example
Run this sample in chrome dev tools
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("jquery12325365345423545423","");
console.log(str)

vb6's mid equivalent for jquery

in vb6 there was a very handy function for string manipulation which could put a character at a certain position of another string and i'm looking for an extended jquery equivalent.
let's say i'm having this string:
var mystring = "__1__";
when applying the function:
var mystring = mid(mystring,4,"x");
it should return __1x_
another example:
var mystring = "";
var mystring = mid(mystring,5,"x");
should return: ____5
i know it requires string manipulation using substr but i was wondering if there's a more elegant way?
thanks
This can be simulated in several ways although there is no such specific function (splice is standard only on Arrays, not Strings).
The easiest one-expression way I know of is with a String.replace when adding to a location "past the end of the string" is not required. Of course String.slice is also a perfectly valid approach, and may be arguably easier to understand.
mystring = "__1__"
// where 3 represents the "characters to skip before inserting"
// and 1 represents the "number of characters to replace"
midstr = mystring.replace(/([^]{3})[^]{0,1}/, "$1x")
Neither the above nor a basic slice will work like the 2nd example without additional prepend-as-needed logic.

Javascript Regex after specific string

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

Categories