regex replace in javascript/jquery - javascript

I've never really used regex so this is probably a basic question, but I need to reformat a string in javascript/jquery and I think regex is the direction to go.
How can I convert this string:
\"1\",\"2\",\"\\",\"\4\"
into:
"1","2","","4"
These are both strings, so really they'd be contained in "" but I thought that may confuse things even more.
I've tried the following but it doesn't work:
var value = '\"1\",\"2\",\"\\",\"\4\"'.replace(/\"/, '"').replace(/"\//, '"');

Try:
var value = your_string.replace(/\\/g, "");
to remove all the "\"

It's a lot of escaping... Your string is:
var str = '\\"1\\",\\"2\\",\\"\\\\",\\"\\4\\"'
console.log(str.replace(/\\/g, '')) // "1","2","","4"
However, if you want only to replace \" with " use:
console.log(str.replace(/\\"/g, '"')) // "1","2","\","\4"

Related

Javascript: add a character to a string containing a specific word

If I have the following string: table.row.columns.values.many. I am looking to add character * after values.
So expected output would be: table.row.columns.values*.many .
If there is no "values" in string then string should stay the same.
Please use this code.
let str = "table.row.columns.values.many"
str = str.replace("values", "values*");
console.log(str);
You can use also "replaceAll" if you want to replace all "values".
I think this works nice for you, really simple, and easy way
var str = "table.row.columns.values.many";
str = str.replace("values", "values*")
console.log(str)

String.replace with special characters noting working

I have spent several hours trying to figure out what is going on here looking at stack overflow and elsewhere and I cannot figure out what is going on. I would really appreciate any help!!
I need to make document.write('< /div>'); go to -> < /div>
I've simplified it down to the simplest possible case with the html example below.
<script>
var str = "document.write('</div>');";
str = str.replace("/document.write/g","");
console.log(str); //</div>
</script>
Exclude the quotes and it works. It is being interpreted as a string literal because of the quotes, whereas a regular expression literal is expressed between plain /s.
Also, . needs to be escaped or it matches any other single character.
<script>
var str = "document.write('</div>');";
str = str.replace(/document\.write/g,"");
console.log(str); //</div>
</script>
String.prototype.replace() accepts either a string or a regex. If you are going with a string this should be:
var str = "document.write('</div>');";
str = str.replace("document.write","");
console.log(str);

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 split().join() thousands separator replacement for .replace() for use on eBay

I use this for comma separated thousands on my site, works great...
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
I'm trying to implement a similar method for ebay using split().join(), since eBay have banned the usage of .replace(), any solution?
I tried using the same regx inside split(), but thus far it has not worked the same way.
Thanks.
maybe you can try to use search() to get the index of the string and remove the characters for the given index.
var pre_string = str.substing(0, found_index);
var post_string = str.substing(found_index + 3);
var replaced_string = pre_string + post_string;
("100,00,0").split(',').join(''); //"100000"
Something like this?
parseInt( ("100,00,0").split(',').join('') ,10); //100000
I think you are referring to:
Javascript .Replace Alternative
In there the code (by WereWolf - The Alpha) is:
String.prototype.fakeReplace=function(str, newstr) {
return this.split(str).join(newstr);
};
var str="Welcome javascript";
str=str.fakeReplace('javascript', '');
alert(str); // Welcome
So, your:
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Becomes:
str.myReplace(/\B(?=(\d{3})+(?!\d))/g, ",");
How?
because .split(STR) splits the string by STR (removing STR in process) into a two element array (or more), and rejoins it with .join(NEWSTR) which places NEWSTR inbetween the two strings in array.
"hello STR world" --.split(STR)--> ["hello "," world"] --.join(NEWSTR)--> "hello NEWSTR world"

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