JS Regex .replace, what am I missing? - javascript

I'm trying to perform a simple regex replace in javascript to replace new lines \n with html breaks
var strings = 'Hello world
This is a test.
Multi-line.';
stringt = strings.replace( '/(\r\n|\n|\r)/gm', '<br />' );
alert(stringt);
Testing the RegEx pattern on a couple of online testers has proven successful, I guess I'm just missing something real dumb?

You can't define strings like that.
You can do multiline strings like this though
var str = "Hello world\n\
This is a test.\n\
Multi-line.";
Then this regexp will work for you
str.replace(/[\r\n]+/g, "<br>");
Notice that regexp in JavaScript are not enclosed in quotes " like they are in langs like PHP.
Per #alex's comment, you could create the regexp like this
var re = new RegExp('[\r\n]+', 'g');
str.replace(re, "<br>");
In this case, you use a string, but no / delimiters.

Related

jQuery - find and replace substring

Let's say I got strings like this
'Hello, I am ***Groot*** today.'
'This is ***not*** my final form.'
'Test test ***123***'
and I want to add some new stuff before the first and after the second asterix to make it look like
'Hello, I am FIRST***Groot***LAST today.'
'This is FIRST***not***LAST my final form.'
'Test test FIRST***123***LAST'
So far I managed to get this
var first = jQuery(this).html().indexOf("***");
var last = jQuery(this).html().lastIndexOf("***");
console.log( jQuery(this).html().substring(first, last+3) );
but I fail on the replacement...so close, yet so far....
You can use regex pretty easily... this will work for all of your strings.
JSFiddle (check js console)
var str = jQuery(this).text();
str = str.replace(/(\*{3}.*\*{3})/, "FIRST$1LAST");
console.log(str);
Also, you don't really need to create the jQuery objects just to get the text, could just do this:
var str = this.innerText;
str = str.replace(/\*{3}.*\*{3}/, "FIRST$&LAST");
console.log(str);
I believe the correct special replacement character in your replacement parameter should be $& rather than $1 just for readability sake and best practices.
$& corresponds to the matched substring, whereas $1 makes it seem like there are multiple matches in the RegExp object.
Reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

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"

regex replace in javascript/jquery

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"

How to replace all the \ from a string with space in javascript?

For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"

How to replace underscores with spaces using a regex in Javascript

How can I replace underscores with spaces using a regex in Javascript?
var ZZZ = "This_is_my_name";
If it is a JavaScript code, write this, to have transformed string in ZZZ2:
var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.replace(/_/g, " ");
also, you can do it in less efficient, but more funky, way, without using regex:
var ZZZ = "This_is_my_name";
var ZZZ2 = ZZZ.split("_").join(" ");
Regular expressions are not a tool to replace texts inside strings but just something that can search for patterns inside strings. You need to provide a context of a programming language to have your solution.
I can tell you that the regex _ will match the underscore but nothing more.
For example in Groovy you would do something like:
"This_is_my_name".replaceAll(/_/," ")
===> This is my name
but this is just language specific (replaceAll method)..
var str1="my__st_ri_ng";
var str2=str1.replace(/_/g, ' ');
Replace "_" with " "
The actual implementation depends on your language.
In Perl it would be:
s/_/ /g
But the truth is, if you are replacing a fixed string with something else, you don't need a regular expression, you can use your language/library's basic string replacement algorithms.
Another possible Perl solution would be:
tr/_/ /
To replace the underscores with spaces in a string, call the replaceAll() method, passing it an underscore and space as parameters, e.g. str.replaceAll('_', ' '). The replaceAll method will return a new string where each underscore is replaced by a space.
const str = 'apple_pear_melon';
// ✅ without regular expression
const result1 = str.replaceAll('_', ' ');
console.log(result1); // 👉️ "apple pear melon"
// ✅ with regular expression
const result2 = str.replace(/_+/g, ' ');
console.log(result2); // 👉️ "apple pear melon"

Categories

Resources