Replace multiple characters in a string using regex - javascript

I want to replace multiple occurrences of multiple characters in a string.Let's say I have a string which contains spaces and / characters. How can I replace both with _?
I know how to replace a single character with the replace() method as below:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
How can I update this to replace multiple characters?

To capture multiple consecutive characters use the + operator in the Regex. Also note that to capture spaces and slashes you can specify them in a character set, for example [\s\/]. Try this:
var s = 'some multi///word/string'.replace(/[\s\/]+/g, '_');
console.log(s);

Define your characters inside a list []
const r = "abc def/ //g h".replace(/[ \/]/g, "_");
console.log(r) // "abc_def____g_h"
To replace multiple, use the + quantifier (one or more occurrences)
const r = "abc def/ //g h".replace(/[ \/]+/g, "_");
console.log(r) // "abc_def_g_h"
To replace the exact sequence " /" (Space+ForwardSlash) with "_"
const r = "abc /def /g /h".replace(/ \/+/g, "_");
console.log(r) // "abc_def_g_h"

Related

Finding ++ in Regular Expression

I want to find ++ or -- or // or ** sign in in string can anyone help me?
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = ++,--,//,**;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
This finds doubles of the characters by a backreference:
/([+\/*-])\1/g
[from q. comments]: i know this but when i type var patt1 = /[++]/i; code find + and ++
[++] means one arbitrary of the characters. Normally + is the qantifier "1 or more" and needs to be escaped by a leading backslash when it should be a literal, except in brackets where it does not have any special meaning.
Characters that do need to be escaped in character classes are e.g. the escape character itself (backslash), the expression delimimiter (slash), the closing bracket and the range operator (dash/minus), the latter except at the end of the character class as in my code example.
A character class [] matches one character. A quantifier, e.g. [abc]{2} would match "aa", "bb", but "ab" as well.
You can use a backreference to a match in parentheses:
/(abc)\1
Here the \1 refers to the first parentheses (abc). The entire expression would match "abcabc".
To clarify again: We could use a quantifier on the backreference:
/([+\/*-])\1{9}/g
This matches exactly 10 equal characters out of the class, the subpattern itself and 9 backreferences more.
/.../g finds all occurrences due to the modifier global (g).
test-case on regextester.com
Define your pattern like this:
var patt1 = /\+\+|--|\/\/|\*\*/;
Now it should do what you want.
More info about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
You can use:
/\+\+|--|\/\/|\*\*/
as your expression.
Here I have escaped the special characters by using a backslash before each (\).
I've also used .test(str) on the regular expression as all you need is a boolean (true/false) result.
See working example below:
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = patt1.test(res);
if (result) {
alert("you cant do this :l");
document.getElementById('screen').innerHTML = '';
}
<div id="screen">
This is some++ text
</div>
Try this:-
As
n+:- Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
We need to use backslash before this special characters.
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
<div id="screen">2121++</div>

Is it possible to do a double replace?

If double replace is it possible to do?
var string = [link="<iframe"qwe"></iframe>"]
var output = string.replace(/[link="([^"]+)"]/g, '$1.replace(/"([^"]+)"/g, "'")');
what i want output:
[link="<iframe'qwe'></iframe>"]
You can use a function as the replacement in replace(). It can then do its own replace on the capture group.
var string = '[link="<iframe"qwe"></iframe>"]';
var output = string.replace(/link="([^\]]+)"]/g, (match, group1) =>
'link="' + group1.replace(/"/g, "'") + '"]');
console.log(output);
Note also that I had to correct your regexp. ([^"]+) should be ([^\]]+) so that it can match a string containing double quotes -- you need to capture that so you can replace the double quotes.
And in the second replacement, you want to match ", not [^"]+

Split string by all spaces except those in parentheses

I'm trying to split text the following like on spaces:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}"
but I want it to ignore the spaces within parentheses. This should produce an array with:
var words = ["Text", "(what is)|what's", "a", "story|fable" "called|named|about", "{Search}|{Title}"];
I know this should involve some sort of regex with line.match(). Bonus points if the regex removes the parentheses. I know that word.replace() would get rid of them in a subsequent step.
Use the following approach with specific regex pattern(based on negative lookahead assertion):
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}",
words = line.split(/(?!\(.*)\s(?![^(]*?\))/g);
console.log(words);
(?!\(.*) ensures that a separator \s is not preceded by brace ((including attendant characters)
(?![^(]*?\)) ensures that a separator \s is not followed by brace )(including attendant characters)
Not a single regexp but does the job. Removes the parentheses and splits the text by spaces.
var words = line.replace(/[\(\)]/g,'').split(" ");
One approach which is useful in some cases is to replace spaces inside parens with a placeholder, then split, then unreplace:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}";
var result = line.replace(/\((.*?)\)/g, m => m.replace(' ', 'SPACE'))
.split(' ')
.map(x => x.replace(/SPACE/g, ' '));
console.log(result);

How to Split string with multiple rules in javascript

I have this string for example:
str = "my name is john#doe oh.yeh";
the end result I am seeking is this Array:
strArr = ['my','name','is','john','&#doe','oh','&yeh'];
which means 2 rules apply:
split after each space " " (I know how)
if there are special characters ("." or "#") then also split but add the characther "&" before the word with the special character.
I know I can strArr = str.split(" ") for the first rule. but how do I do the other trick?
thanks,
Alon
Assuming the result should be '&doe' and not '&#doe', a simple solution would be to just replace all . and # with & split by spaces:
strArr = str.replace(/[.#]/g, ' &').split(/\s+/)
/\s+/ matches consecutive white spaces instead of just one.
If the result should be '&#doe' and '&.yeah' use the same regex and add a capture:
strArr = str.replace(/([.#])/g, ' &$1').split(/\s+/)
You have to use a Regular expression, to match all special characters at once. By "special", I assume that you mean "no letters".
var pattern = /([^ a-z]?)[a-z]+/gi; // Pattern
var str = "my name is john#doe oh.yeh"; // Input string
var strArr = [], match; // output array, temporary var
while ((match = pattern.exec(str)) !== null) { // <-- For each match
strArr.push( (match[1]?'&':'') + match[0]); // <-- Add to array
}
// strArr is now:
// strArr = ['my', 'name', 'is', 'john', '&#doe', 'oh', '&.yeh']
It does not match consecutive special characters. The pattern has to be modified for that. Eg, if you want to include all consecutive characters, use ([^ a-z]+?).
Also, it does nothing include a last special character. If you want to include this one as well, use [a-z]* and remove !== null.
use split() method. That's what you need:
http://www.w3schools.com/jsref/jsref_split.asp
Ok. i saw, you found it, i think:
1) first use split to the whitespaces
2) iterate through your array, split again in array members when you find # or .
3) iterate through your array again and str.replace("#", "&#") and str.replace(".","&.") when you find
I would think a combination of split() and replace() is what you are looking for:
str = "my name is john#doe oh.yeh";
strArr = str.replace('\W',' &');
strArr = strArr.split(' ');
That should be close to what you asked for.
This works:
array = string.replace(/#|\./g, ' &$&').split(' ');
Take a look at demo here: http://jsfiddle.net/M6fQ7/1/

Regular Expression: Any character that is not a letter or number

I need a regular expression that will match any character that is not a letter or a number. Once found I want to replace it with a blank space.
To match anything other than letter or number you could try this:
[^a-zA-Z0-9]
And to replace:
var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');
This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.
\W
For example in JavaScript:
"(,,#,£,() asdf 345345".replace(/\W/g, ' '); // Output: " asdf 345345"
You are looking for:
var yourVar = '1324567890abc§$)%';
yourVar = yourVar.replace(/[^a-zA-Z0-9]/g, ' ');
This replaces all non-alphanumeric characters with a space.
The "g" on the end replaces all occurrences.
Instead of specifying a-z (lowercase) and A-Z (uppercase) you can also use the in-case-sensitive option: /[^a-z0-9]/gi.
This is way way too late, but since there is no accepted answer I'd like to provide what I think is the simplest one: \D - matches all non digit characters.
var x = "123 235-25%";
x.replace(/\D/g, '');
Results in x: "12323525"
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Match letters only /[A-Z]/ig
Match anything not letters /[^A-Z]/ig
Match number only /[0-9]/g or /\d+/g
Match anything not number /[^0-9]/g or /\D+/g
Match anything not number or letter /[^A-Z0-9]/ig
There are other possible patterns
try doing str.replace(/[^\w]/);
It will replace all the non-alphabets and numbers from your string!
Edit 1: str.replace(/[^\w]/g, ' ')
Just for others to see:
someString.replaceAll("([^\\p{L}\\p{N}])", " ");
will remove any non-letter and non-number unicode characters.
Source
To match anything other than letter or number or letter with diacritics like é you could try this:
[^\wÀ-úÀ-ÿ]
And to replace:
var str = 'dfj,dsf7é#lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');
Inspired by the top post with support for diacritics
source
Have you tried str = str.replace(/\W|_/g,''); it will return a string without any character and you can specify if any especial character after the pipe bar | to catch them as well.
var str = "1324567890abc§$)% John Doe #$#'.replace(/\W|_/g, ''); it will return str = 1324567890abcJohnDoe
or look for digits and letters and replace them for empty string (""):
var str = "1324567890abc§$)% John Doe #$#".replace(/\w|_/g, ''); it will return str = '§$)% #$#';
Working with unicode, best for me:
text.replace(/[^\p{L}\p{N}]+/gu, ' ');

Categories

Resources