Find and Replace using Regular Expression - javascript

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

Related

Doesn't get JavaScript RegEx to work

Need help getting the following JavaScript RegEx case insensitive:
^(ABCDE)\d{5}$
I have tried /i but it doesn't work:
^(ABCDE)\d{5}$/i
Where should I place /i to get it to work?
Thanks in advance.
When you have a literal regex notation, just use /.../:
var re = /^(ABCDE)\d{5}$/i;
If you use a RegExp constructor:
var re = RegExp("^(ABCDE)[0-9]{5}$", "i");
However, the literal notation is preferable here since the pattern is constant, known from the beginning, and no variables are used to build it dynamically. Note that if you were to use \d in the RegExp constructor, you'd have to double the backslashes:
var re = RegExp("^(ABCDE)\\d{5}$", "i");
Try to write it this way :
var regex = /^(ABCDE)\d{5}$/i;
It needs the first / or you can also use
var regex = new RegExp('^(ABCDE)\\d{5}$', 'i');
Then if you try in a console this it should work (online testers can add other issue, just try directly on your code) :
regex.test('ABCDE12345') // true
regex.test('abcde12345') // true
Test on Regex101 : https://regex101.com/r/zR5yR0/1

using regular expression to get strings among commas

I am doing some JavaScript coding and have to process a string to a array.
The original string is this: "red,yellow,blue,green,grey"
What I want to get is an array like this: ["red","yellow","blue","green","grey"]
I have tried to write a function to do this, use indexOf() to get the position of commas then do some further processing. But I think it's to heavy this way. Is there a better way to use regular expression or some existed JavaScript method to implement my purpose?
Thanks all.
use string.split function to split the original string by comma.......
string.split(",")
You can use split:
The split() method splits a String object into an array of strings by separating the string into substrings.
var arr = "red,yellow,blue,green,grey".split(',');
OR
You can also use regex:
var arr = "red,yellow,blue,green,grey".match(/\w+/g);
Try the string.split() method. For further details refer to:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
you can use .split() function.
Example
.split() : Split a string into an array of substrings:
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
alert(res);
You can use following regular expression ..
[^,]*

JavaScript String.replace() all instances and escaping

I have a string: Dkjd(Dk39dD_2=3499(39482&#6293jd
I would like to escape all characters of my choosing (say, _#-) with a backslash. I'm confused how I would do this with String.replace. Can I use the original value in the new value var? Can I use RegEx to do this? Thanks.
No need to use function, use backreference:
source.replace(/([_#\-])/g, "\\$1")
The thing in parentheses can be referenced as $1 in replacement string.
This should be easy with a regex.
var str = 'Dkjd(Dk39dD_2=3499(39482&#6293jd';
str = str.replace(/[_#-]/g, function(match){
return '\\'+match;
});
console.log(str); // Dkjd(Dk39dD\_2=3499(39482&\#6293jd
Simply,
var str = 'Dkjd(Dk39dD_2=3499(39482&#6293jd';
str = str.replace(/([_#-])/g, '\\$1');
Hope it helps.

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.

Regular Expression - Search and Replace

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

Categories