replace all occurrences in a string [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fastest method to replace all instances of a character in a string
How can you replace all occurrences found in a string?
If you want to replace all the newline characters (\n) in a string..
This will only replace the first occurrence of newline
str.replace(/\\n/, '<br />');
I cant figure out how to do the trick?

Use the global flag.
str.replace(/\n/g, '<br />');

Brighams answer uses literal regexp.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example

As explained here, you can use:
function replaceall(str,replace,with_this)
{
var str_hasil ="";
var temp;
for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
{
if (str[i] == replace)
{
temp = with_this;
}
else
{
temp = str[i];
}
str_hasil += temp;
}
return str_hasil;
}
... which you can then call using:
var str = "50.000.000";
alert(replaceall(str,'.',''));
The function will alert "50000000"

Related

capitalise first letter - CAN'T Use 'toUpperCase' (JS) [duplicate]

This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 7 years ago.
function to capitalise first letter of a string - 'toUpperCase' , underscore and other jQuery are excluded . I reworked a vers with underscore which I can't use
```
function capitalize (str){
var str = "";
var lowercase = "";
var Uppercase = "";
str.forEach(){
for (i=0; i < str.length; i++);
}
return Uppercase[lowercase.indexOf(str0)];
}
```
There are lots of reduced vers using toUpperCase
Any links, code help pls .... Tks
The best method I've found is just to call toUpperCase on the first character and concat the rest of the string using slice:
function capitalize(str) {
if(typeof str === 'string') {
return str[0].toUpperCase() + str.slice(1);
}
return str;
}
If you want to capitalize each word in a sentence, you can split on space:
"capitalize each word of this sentence".split(' ').map(capitalize).join(' ');

JS Regex: Replace all but first [duplicate]

This question already has an answer here:
use regex to replace all but first occurrence of a substring of blanks
(1 answer)
Closed 9 years ago.
How can I make a Regex which replaces all occurrences of a word but the first?
I have a webpage with loads of text and a header at the top. I want to make a regex which replaces all occurrences of a word but the first because I don't want the header to change.
var count = 0;
text = text.replace(myRegex, function(match) {
count++;
if(count==1) {
return match;
}
else {
return myReplacedValue;
}
});
You could do this:
var i = 0;
"foo foo foo".replace(/foo/g, function(captured/*, offset, originalString */) {
if ( i++ ) {
return 'bar';
}
return captured;
});
great answer abstract... i have never seen replace used like that before
heres a nice cluttered version..
text = text.replace(/boo/g, function(match) {return (++count==1)?match:myReplacedValue});

get detailed substring

i have a problem i'm trying to solve, i have a javascript string (yes this is the string i have)
<div class="stories-title" onclick="fun(4,'this is test'); navigate(1)
What i want to achieve are the following points:
1) cut characters from start until the first ' character (cut the ' too)
2) cut characters from second ' character until the end of the string
3) put what's remaining in a variable
For example, the result of this example would be the string "this is test"
I would be very grateful if anyone have a solution.. Especially a simple one so i can understand it.
Thanks all in advance
You can use split() function:
var mystr = str.split("'")[1];
var newstr = str.replace(/[^']+'([^']+).*/,'$1');
No need to cut anything, you just want to match the string between the first ' and the second ' - see similar questions like Javascript RegExp to find all occurences of a a quoted word in an array
var string = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var m = string.match(/'(.+?)'/);
if (m)
return m[1]; // the matching group
You can use regular expressions
/\'(.+)\'/
http://rubular.com/r/RcVmejJOmU
http://www.regular-expressions.info/javascript.html
If you want to do the work yourself:
var str = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var newstr = "";
for (var i = 0; i < str.length; i++) {
if (str[i] == '\'') {
while (str[++i] != '\'') {
newstr += str[i];
}
break;
}
}

How to use replaceAll() in Javascript.........................? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I am using below code to replace , with \n\t
ss.replace(',','\n\t')
and i want to replace all the coma in string with \n so add this ss.replaceAll(',','\n\t') it din't work..........!
any idea how to get over........?
thank you.
You need to do a global replace. Unfortunately, you can't do this cross-browser with a string argument: you need a regex instead:
ss.replace(/,/g, '\n\t');
The g modifer makes the search global.
You need to use regexp here. Please try following
ss.replace(/,/g,”\n\t”)
g means replace it globally.
Here's another implementation of replaceAll.
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Then you can use it like:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

How to globally replace a forward slash in a JavaScript string?

How to globally replace a forward slash in a JavaScript string?
The following would do but only will replace one occurence:
"string".replace('/', 'ForwardSlash');
For a global replacement, or if you prefer regular expressions, you just have to escape the slash:
"string".replace(/\//g, 'ForwardSlash');
Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.
var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);
You need to wrap the forward slash to avoid cross browser issues or //commenting out.
str = 'this/that and/if';
var newstr = str.replace(/[/]/g, 'ForwardSlash');
Without using regex (though I would only do this if the search string is user input):
var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!'
Is this what you want?
'string with / in it'.replace(/\//g, '\\');
This has worked for me in turning "//" into just "/".
str.replace(/\/\//g, '/');
Hi a small correction in the above script..
above script skipping the first character when displaying the output.
function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
if(x.charAt(i) == "/")
{
y += "";
}
else
{
y+= x.charAt(i);
}
}
return y;
}
This is Christopher Lincolns idea but with correct code:
function replace(str,find,replace){
if (find){
str = str.toString();
var aStr = str.split(find);
for(var i = 0; i < aStr.length; i++) {
if (i > 0){
str = str + replace + aStr[i];
}else{
str = aStr[i];
}
}
}
return str;
}
Example Usage:
var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');
Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.
Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:
function replace(str,find,replace){
if (find){
str = str.toString().split(find).join(replace);
}
return str;
}
var str = '/questions'; // input: "/questions"
while(str.indexOf('/') != -1){
str = str.replace('/', 'http://stackoverflow.com/');
}
alert(str); // output: "http://stackoverflow.com/questions"
The proposed regex /\//g did not work for me; the rest of the line (//g, replacement);) was commented out.
You can create a RegExp object to make it a bit more readable
str.replace(new RegExp('/'), 'foobar');
If you want to replace all of them add the "g" flag
str.replace(new RegExp('/', 'g'), 'foobar');

Categories

Resources