How to replace all \" in a JS string? - javascript

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);
​

Related

How to replace all the zeros in javascript

How can I replace all the zeroes with asterisks in a string?
I've tried:
var a = "00000004567";
a.replace(/0*\d/g,'*');
The problem is that it returns: "****567", which is undesirable.
var a = '00000004567';
a.replace(/0/g, '*');
Remove the *\d to convert all the zeroes to asterisks. The g modifier will handle the rest.
var a = "00000004567";
console.log(a.replace(/0/g, '*'))
Assuming you're talking about a string, use the global modifier like this:
a.replace(/0/g,"*");

how to make a regexp in js split to break using special text characters

I need help to make this work in JS:
a="casa-me,pois estou farto! Eis a lista:uma;duas;três."
a.split(/regex/) to return
a=["casa","me","pois","estou","farto","Eis","a","lista","uma","duas","três"]
Thank you.
Other answers seem to miss things like accented characters, etc. This seems to be working well against your test string, though:
var re = /[^A-zÀ-ÿ]+/g;
var str = 'casa-me,pois estou farto! Eis a lista:uma;duas;três';
var result = str.split(re);
alert(result);
here you go:
a.match(/\w+/g).join(' ');
What you want is a global matching regex (note the g modifier):
yourString.replace(/[,;:.!]/g, ' ')
Regexp is something very nice.
var a = 'casa-me,pois estou farto! Eis a lista:uma;duas;três.';
var array = a.match(/[àáâãèéêẽìíîĩòóôõùúûũ\w]+/g);
Each array position will have a word as you want.

JavaScript does not replace the last symbol of the string

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, ''');

myString.replace( VARIABLE, "") ...... but globally

How can I use a variable to remove all instances of a substring from a string?
(to remove, I'm thinking the best way is to replace, with nothing, globally... right?)
if I have these 2 strings,
myString = "This sentence is an example sentence."
oldWord = " sentence"
then something like this
myString.replace(oldWord, "");
only replaces the first instance of the variable in the string.
but if I add the global g like this myString.replace(/oldWord/g, ""); it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?
Well, you can use this:
var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");
You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.
var oldWordRegEx = new RegExp(oldWord,'g');
myString.replace(oldWordRegEx,"");
No need to use a regular expression here: split the string around matches of the substring you want to remove, then join the remaining parts together:
myString.split(oldWord).join('')
In the OP's example:
var myString = "This sentence is an example sentence.";
var oldWord = " sentence";
console.log(myString.split(oldWord).join(''));
According to the docs at MDN, you can do this:
var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = str.replace(re, 'oranges');
console.log(newstr); // oranges are round, and oranges are juicy.
where /gi tells it to do a global replace, ignoring case.

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

Categories

Resources