How to globally replace pipe symbol "|" in string - javascript

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

Related

replace multiple consecutive hyphens with one

Is this possible in Javascript?
I have this from Java, but can not be used in Javascript.
s/-{2,}/-/g
Is there another way that works?
Yes it is. You can use the same regex with the Javascript replace() method.
s.replace(find, replacement)
// where 's' is your string object
Example:
var r = 'foo--bar---baz'.replace(/-{2,}/g, '-');
console.log(r); // "foo-bar-baz"
You can just do this:
var newStr = "hi--this is----good".replace(/-+/g,'-'); // hi-this is-good
-+ matches more than 1 - and replaces them with a single -
Your regex is also valid. Except you cannot use s modifier.
query.trim().replace(/\s\s+/g, '-').replace(/[\s.;,?%]/, '-')

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"

javascript delete all occurrences of a char in a string

I want to delete all characters like [ or ] or & in a string i.E. :
"[foo] & bar" -> "foo bar"
I don't want to call replace 3 times, is there an easier way than just coding:
var s="[foo] & bar";
s=s.replace('[','');
s=s.replace(']','');
s=s.replace('&','');
Regular expressions [xkcd] (I feel like him ;)):
s = s.replace(/[\[\]&]+/g, '');
Reference:
MDN - string.replace
MDN - Regular Expressions
http://www.regular-expressions.info/
Side note:
JavaScript's replace function only replaces the first occurrence of a character. So even your code would not have replaced all the characters, only the first one of each. If you want to replace all occurrences, you have to use a regular expression with the global modifier.
Today, in 2021 you can use the replaceAll function:
let str = "Hello. My name is John."
let newStr = str.replaceAll('.', '')
console.log(newStr) // result -> Hello My name is John
let nextStr = str.replaceAll('.', '&')
console.log(nextStr) // result -> Hello& My name is John&

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"

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

Categories

Resources