JavaScript does not replace the last symbol of the string - javascript

I have try to replace a symbol in JavaScript, but somehow this is always only replace the 1st symbol of the string instead of replaced all the symbol.
JavaScript:
var note = "test'test'test'";
note = note .replace("'", "'");
Output:
test'test'test'
Does anyone know how can I can replace all ' symbols with ' ??

Use regex substitution and add a g flag to make it global:
> "test'test'test'".replace(/'/g, ''');
"test'test'test'"

Use g suffix for the Global substituation.
This is the right way:
note = "test'test'test'";
note.replace(/\'/g,"'")
Check this: jsfiddle

Try this note.replace(/\'/g, ''');

Related

How to globally replace pipe symbol "|" in string

How can I globally replace the | (pipe) symbol in a string? When I try to replace it with "so|me|str|ing".replace(/|/g, '-'), I get "-s-o-|-m-e-|-s-t-r-|-i-n-g-"
| has special meaning (A|B means "match A or B"), so you need to escape it:
"so|me|str|ing".replace(/\|/g, '-');
| means OR, so you have to escape it like this: \|
Try using "so|me|str|ing".replace(/[|]/g, '-')
This is a great resource for working with RegEx: https://www.regex101.com/
In my case, the pipe was coming as an variable, so I couldn't use any of these solutions. Instead, You can use:
let output_delimiter ='|';
let str= 'Foo|bar| Test';
str.replace(new RegExp('[' + output_delimiter + ']', 'g'), '-')
//should be 'Foo-bar- Test'
Another solution is, to do a substring replacement instead of a regex to replace the pipe character. However, the String.prototype.replace() method will only replace the first substring instance, like here:
"so|me|str|ing".replace("|", "-"); // "so-me|str|ing" → WRONG
Possible workarounds:
Split the string into an array and join it with the new delimiter:
"so|me|str|ing".split("|").join("-"); // "so-me-str-ing" → RIGHT
Use a loop to replace one substring after the other.
var str = "so|me|str|ing";
while(str.indexOf("|") >= 0) {
str = str.replace("|", "-"); // "so-me|str|ing" → RIGHT
}
Use .replaceAll()
Use the modern approach String.prototype.replaceAll() -- beware, that this method is only supported by a few browsers yet:
"so|me|str|ing".replaceAll("|", "-"); // "so-me-str-ing" → RIGHT

Variable in match (javascript)

<body class="reviews"></body>
var body = document.body;
var target = 'reviews';
if (body.className.match('/\b' + target + '\b/'))
console.log(true);
else
console.log(false);
This code returns false. But if I use body.className.match(/\breviews\b/) it returns true.
What's wrong with it?
I tried to escape a variable in a regex, no luck.
You are searching for the literal string '/\breviews\b/', it's not being read as a RegEx.
You need to use the new RegExp method.
body.className.match(new RegExp('\\b' + target + '\\b'))
Note: Don't use delimiters with new RegExp. Also, note that \\b has 2 \.

How to replace all \" in a JS string?

How to replace all \" to " in a string?
I tried, but it doesn't works: var foobar = ("foo\\\"bar\\\"foo").replace(/"\\\""/,'"');
The result is foo\"bar\"foo , but it should be foo"bar"foo
You don't need to use quotes inside of a RegEx pattern, the // delimiters act as ones.
var foobar = "foo\\\"bar\\\"foo".replace(/\\"/g,'"');
Works for me.
Try .replace(/\\"/g,'"'); - regexes don't need quotes around them, I'm surprised you get any result at all.
You need to fix your regex, you need to do
replace(/\\\"/g, "\"")
Your quoting is wrong and you're not using g - global flag. It should be:
var foobar = ("foo\\\"bar\\\"foo").replace(/\\"/g,'"');
Try defining it like this
var foobar = ("foo\\\"bar\\\"foo").replace(/"\\\""/g,'"');
note that the .replace has a /g which makes it global
jsfiddle
// initial string
var str = "AAAbbbAAAccc";
// replace here
str = str.replace(/A/g, "Z");
alert(str);
​

How do I replace all occurrences of "/" in a string with "_" in JavaScript?

For some reason the "".replace() method only replaces the first occurrence and not the others. Any ideas?
You have to use the g modifier (for global) in your replace call.
str = str.replace(/searchString/g, "replaceWith")
In your particular case it would be:
str = str.replace (/\//g, "_");
Note that you must escape the / in the regular expression.
"Your/string".split("/").join("_")
if you don't require the power of RegExp
str.replace(/\//g,”_”)
Try this code:
text = text.replace(new RegExp("textToReplace","g"), "replacemntText"));

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources