replace multiple consecutive hyphens with one - javascript

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.;,?%]/, '-')

Related

remove last part of string following '&&&' with JavaScript Regex

I'm trying to use a regex in JS to remove the last part of a string. This substring starts with &&&, is followed by something not &&&, and ends with .pdf.
So, for example, the final regex should take a string like:
parent&&&child&&&grandchild.pdf
and match
parent&&&child
I'm not that great with regex's, so my best effort has been something like:
.*?(?:&&&.*\.pdf)
Which matches the whole string. Can anyone help me out?
You may use this greedy regex either in replace or in match:
var s = 'parent&&&child&&&grandchild.pdf';
// using replace
var r = s.replace(/(.*)&&&.*\.pdf$/, '$1');
console.log(r);
//=> parent&&&child
// using match
var m = s.match(/(.*)&&&.*\.pdf$/)
if (m) {
console.log(m[1]);
//=> parent&&&child
}
By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input.
You want to remove the last portion, so replace it
var str = "parent&&&child&&&grandchild.pdf"
var result = str.replace(/&&&[^&]+\.pdf$/, '')
console.log(result)

RegExp to filter characters after the last dot

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"

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

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 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