Regular Expression - Search and Replace - javascript

I'm new to regular expression and have come across a problem.
I want to do a search and replace on a string.
Search for an instance of -- and ' and replace it with - and `, respectively.
Example
Current String: Hi'yo every--body!
Replaced String: Hi`yo every-body!
Any help would greatly be appreciated!

You need.
"Hi'yo every--body!".replace(/--/g, '-').replace(/'/,'`')
Make a function
function andrew_styler(s){return s.replace(/--/g, '-').replace(/'/,'`');}

If you want just replace -- with - use the simplest regexp:
var str = "Hi'yo every--body!";
str = str.replace(/--/g, '-');
The flag g turns the global search on, so that pattern replace all occurances.

#dfsq is correct, regexp is overkill for a couple of simple replaces but for reference.
var s = "Hi'yo every--body!";
s = s.replace(/'/g, "`").replace(/\-{2}/g, "-");

Related

JavaScript - strip everything before and including a character

I am relatively new to RegEx and am trying to achieve something which I think may be quite simple for someone more experienced than I.
I would like to construct a snippet in JavaScript which will take an input and strip anything before and including a specific character - in this case, an underscore.
Thus 0_test, 1_anotherTest, 2_someOtherTest would become test, anotherTest and someOtherTest, respectively.
Thanks in advance!
You can use the following regex (which can only be great if your special character is not known, see Alex's solution for just _):
^[^_]*_
Explanation:
^ - Beginning of a string
[^_]* - Any number of characters other than _
_ - Underscore
And replace with empty string.
var re = /^[^_]*_/;
var str = '1_anotherTest';
var subst = '';
document.getElementById("res").innerHTML = result = str.replace(re, subst);
<div id="res"/>
If you have to match before a digit, and you do not know which digit it can be, then the regex way is better (with the /^[^0-9]*[0-9]/ or /^\D*\d/ regex).
Simply read from its position to the end:
var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

Regex Replace issue

I tried to use regex replace method to replace xxx="yyy" pattern of text in given string like.
My pattern is : /^[a-zA-Z0-9.;:|_-]+="[a-zA-Z0-9.;:_-]+\"/
Code:
var userinput = '<div id="c16430" style="color:red;" class="css-btn">';
var pattern = /^[a-zA-Z0-9.;:|_-]+="[a-zA-Z0-9.;:_-]+\"/;
userinput = userinput.replace( pattern, "Replaced..." );
But it is not working... jsfiddle. What is wrong?
Thanks in advance..
You have a couple of problems:
You are trying to match the start of the input, using ^ at the start
You are not using the global flag /g at end, so it would only replace the first match.
This will work:
var pattern = /[a-zA-Z0-9.;:|_-]+="[a-zA-Z0-9.;:_-]+\"/g;
Here is your updated example
Simplified for you. As stated this could match false input, not knowing how strict your input is.
var pattern = /[^ =]+="[^"]+"/g;
or ignore non-word characters
var pattern = /[^\W]+="[^"]+"/g;
or stick with the original idea, the i modifier is used to perform case-insensitive matching.
var pattern = /[a-z0-9_.|:;-]+="[^"]+"/ig;
It is perfect
/\s[^=]+\=\".*?\"/g

Find and Replace using Regular Expression

Well the answer should be very simple.But i am new to the regular expression.
What i want to do is just find and replace :
Eg: iti$%#sa12c##ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters
In the above sentence replace the words "of" with "in"
I tried this but didn't get the result, please help me out.
string="iti$%#sa12c##ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters";
var string2=string.replace("/(\w*\W*)of(\w*\W*)/g","$1in$2");
console.warn(string2);
Fix the regex literal (no quotes) and use word boundaries (\b, no need to use $1 and $2) :
var string2 = string.replace(/\bof\b/g, "in");
Why not a simple var replaced = yourString.replace(/of/g, 'in');?
Globally replace without using a regex.
function replaceMulti(myword, word, replacement) {
return myword.split(word).join(replacement);
}
var inputString = 'iti$%#sa12c##ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters';
var outputString = replaceMulti(inputString, 'of', 'in');
Like this?
str.replace("of","in");
Regular expressions are literals or objects in JavaScript, not strings.
So:
/(\w*\W*)of(\w*\W*)/g
or:
new Regexp("(\\w*\\W*)of(\\w*\\W*)","g");

How to use a variable value as a regex pattern

I am desperate - I don't see what I'm doing wrong. I try to replace all occurrences of '8969' but I always get the original string (no matter whether tmp is a string or an int). Maybe it's already too late, maybe I'm blind, ...
var tmp = "8969";
alert("8969_8969".replace(/tmp/g, "99"));
Can someone help me out?
The / characters are the container for a regular expression in this case. 'tmp' is therefore not used as a variable, but as a literal string.
var tmp = /8969/g;
alert("8969_8969".replace(tmp, "99"));
alert("8969_8969".replace(/8969/g, "99"));
or
var tmp = "8969"
alert("8969_8969".replace(new RegExp(tmp,"g"), "99"));
Live DEMO
Dynamic way of handling a regex:
var nRegExp = new RegExp("8969", 'g');
alert("8969_8969".replace(nRegExp, "99"));
/tmp/g. This is a regex looking for the phrase "tmp". You need to use new RegExp to make a dynamic regex.
alert("8969_8969".replace(new RegExp(tmp,'g'), "99"));
Javascript doesn't support that usage of tmp, it will try to use 'tmp' literally, as a regex pattern.
"8969_8969".replace(new RegExp(tmp,'g'), "99")

Categories