Chain replace for the same character appearing multiple times - javascript

Let's say I have a string like so
Danny is ? James is ? Allen is ?
And I want to replace it to
Danny is great James is wonderful Allen is magnificent
How can I use replace to do it?
I'm attempting to do something like
string.replace(/\?/g, 'great ').replace(/\?/g, 'wonderful ').replace(/\?/g, 'magnificent');
but I just get:
Danny is great James is great Allen is great
If the case was something like:
Danny is ? James is # Allen is $
string.replace(/\?/g, 'great ').replace(/\#/g, 'wonderful ').replace(/\$/g, 'magnificent');
It would work as expected, but since it's the same character it's not working.
Is there a neater way to achieve this than doing something like below?
string = string.replace(/\?/g, 'great ')
string = string.replace(/\?/g, 'wonderful ')
string = string.replace(/\?/g, 'magnificent');

You are using the replace function with a regular expression with the /g (meaning: "global") option, which means it will replace the '?' everywhere in the string.
To replace only one occurence of '?' at a time, just use a normal string to find, eg: string.replace('?', 'great')
So, your full example would be:
string = string.replace('?', 'great ')
string = string.replace('?', 'wonderful ')
string = string.replace('?', 'magnificent');

Related

How do I replace all emails in string with the same email formatted in JavaScript [duplicate]

I have a string in JavaScript in which I'd like to find all matches of a given phrase and wrap them with a tag. I haven't been able to find the right regex method here to replace a case insensitive phrase and replace it with itself with additional text around it. For example:
Input string:
"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."
Case insensitive phrase: "cat"
Output string:
"I like to play with <em>cat</em>s, as does <em>Cat</em>hy, who is a member of A<em>CAT</em>A, which is the American <em>Cat</em> And Tiger Association."
So, basically, inject <em></em> around any matches. I can't just do a straight-up replace, because I'll lose the original case in the input string.
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
You can do straight-up replace by using a replace function:
str.replace(/cat/ig, function replace(match) {
return '<em>' + match + '</em>';
});
One needs no capturing group around the whole regex because there is a $& placeholder that refers to the whole match from the string replacement pattern:
"Foo bar cat".replace(/cat/ig, "<em>$&</em>");
^^
See the Specifying a string as a parameter section:
$& Inserts the matched substring.
Thus, no need of any callback methods or redundant regex constructs.
You can solve it very simple, just use a capturing group with the word you want, and then use the replacement string <em>$1</em>. You can use a regex like this:
(cat)
working demo
Below, you can see in green the matches (capturing the word cat insensitively) and in the substitution section you can see the replacements.
You can use this code:
var re = /(cat)/ig;
var str = '"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."\n';
var subst = '<em>$1</em>';
var result = str.replace(re, subst);

Regex conditional search javascript [duplicate]

I have a string in JavaScript in which I'd like to find all matches of a given phrase and wrap them with a tag. I haven't been able to find the right regex method here to replace a case insensitive phrase and replace it with itself with additional text around it. For example:
Input string:
"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."
Case insensitive phrase: "cat"
Output string:
"I like to play with <em>cat</em>s, as does <em>Cat</em>hy, who is a member of A<em>CAT</em>A, which is the American <em>Cat</em> And Tiger Association."
So, basically, inject <em></em> around any matches. I can't just do a straight-up replace, because I'll lose the original case in the input string.
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
You can do straight-up replace by using a replace function:
str.replace(/cat/ig, function replace(match) {
return '<em>' + match + '</em>';
});
One needs no capturing group around the whole regex because there is a $& placeholder that refers to the whole match from the string replacement pattern:
"Foo bar cat".replace(/cat/ig, "<em>$&</em>");
^^
See the Specifying a string as a parameter section:
$& Inserts the matched substring.
Thus, no need of any callback methods or redundant regex constructs.
You can solve it very simple, just use a capturing group with the word you want, and then use the replacement string <em>$1</em>. You can use a regex like this:
(cat)
working demo
Below, you can see in green the matches (capturing the word cat insensitively) and in the substitution section you can see the replacements.
You can use this code:
var re = /(cat)/ig;
var str = '"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."\n';
var subst = '<em>$1</em>';
var result = str.replace(re, subst);

How to add letters / words / characters to a special word in a string in javascript?

Let us consider we have a string str and a function addify() and we can do something like this with it :
var str = "I am #java";
console.log(addify(str, "script");
//=> I am #javascript
So, you may understand what happened ! The addify() finds all the words with the special character # and then adds our desired words or letter or any character to it. Another example :
var str = "I wrote a #s in #javas";
console.log(addify(str, " cript");
//=> I wrote a #script in #javascript
So, can anyone teach me how to make the addify() function ?
Thanks in advance
Find substring in Javascript and prepend/append some characters
StackOverflow to the rescue!
At the provided link you can find a regex example on how you can identify a special character within a provided string and then edit the result using the string .replace() method...
Quick breakdown of the regex: find the (\w+) word after the string # which is then represented as $1 as the second parameter in the string .replace() method where you can modify the string into a new format.
Bonus points: this will only find instances where the string being searched is connected to another word. If you targeted identifier (#) exists alone, then it will not update a blank space.
function addify( str, ending ){
return str.replace(/#(\w+)/g, `#$1${ending}`);
}
console.log( addify( 'i like #cheese', 'burgers' ) );
console.log( addify( 'party # my place', 'not!' ) );

Search to extract words inside single quotes or double quotes from a sentence. in javascript

Example :work "work & work
Result : ["work & work"]
Example : Exercise is "good" for "health"
Result : ["good", "health"]
I wanted them in javascript
You can do
function getResult(str){
return str.split('"').filter((e, i) => (i&1))
}
console.log(getResult('work "work & work'));
console.log(getResult('Exercise is "good" for "health"'));
This answer is what you're looking for, including the snippet below with explanation for quick reference.
(["'])(?:(?=(\\?))\2.)*?\1
As an example using Javascript:
function getWordsBetweenQuotes(str) {
return str.match(/(["'])(?:(?=(\\?))\2.)*?\1/g);
}
([""']) match a quote; ((?=(\?))\2.) if backslash exists, gobble it, and whether or not that happens, match a character; *? match many times (non-greedily, as to not eat the closing quote); \1 match the same quote that was use for opening.
Maybe a regexp like this will work:
str.match(/\w+|"[^"]+"/g)
var words = 'Exercise is "good" for "health"'.match(/(?<=")([\w]*?)(?=")/g);
console.log(words)

Regex to replace non A-Z characters plus specific strings

I'm trying to build a regex (for Javascript) that basically does /([\s\W])+/g, with the addition of specific strings (case-insensitive).
Right now I'm doing it like:
var a = 'Test 123 Enterprises PTY-Ltd&Llc.';
a.toLowerCase()
.replace('pty','')
.replace('ltd','')
.replace('llc','')
.replace(/([\s\W])+/g, '');
// Result: 'test123enterprises'
Of course, I'd love to be able to wrap this all into one replace() method, but I can't find any documentation online on how to achieve this via regex. Is this possible?
Try this:
a.toLowerCase().replace(/pty|ltd|llc|\W+/g,'');
It uses the pipe which is basically an OR operator for regular expressions.
You can use a logical OR :
/pty|ltd|llc|([\s\W])+/g
You can use an alternation operator | to specify alternatives:
var re = /\b(?:pty|ltd|llc)\b|\W+/gi;
var str = 'Test 123 Enterprises PTY-Ltd&Llc.';
var result = str.replace(re, '').toLowerCase();
alert(result);
To remove pty, ltd and llc as whole words, you need to use word boundary \b. Also, you need no capturing group since you are not using it. Also, \W includes \s, no need to repeat it.

Categories

Resources