Replace all spaces except the first & last ones - javascript

I want to replace all whitespaces except the first and the last one as this image.
How to replace only the red ones?
how to replace the red space
I tried :
.replace(/\s/g, "_");
but it captures all spaces.

I suggest match and capture the initial/trailing whitespaces that will be kept and then matching any other whitespace that will be replaced with _:
var s = " One Two There ";
console.log(
s.replace(/(^\s+|\s+$)|\s/g, function($0,$1) {
return $1 ? $1 : '_';
})
);
Here,
(^\s+|\s+$) - Group 1: either one or more whitespaces at the start or end of the string
| - or
\s - any other whitespace.
The $0 in the callback method represents the whole match, and $1 is the argument holding the contents of Group 1. Once $1 matches, we return its contents, else, replace with _.

You can use ^ to check for first character and $ for last, in other words, search for space that is either preceded by something other than start of line, or followed by something thing other than end of line:
var rgx = /(?!^)(\s)(?!$)/g;
// (?!^) => not start of line
// (?!$) => not end of line
console.log(' One Two Three '.replace(rgx, "_"));

Related

Javascript match a string which start with a specific char from the set of chars and end with same char using Regular Expression

I need to achieve a particular task in javascript, in which my goal is to match the string which starts with a char from a specific set of characters like vowel and ends with the same character where the length of the string is greater than three.
so far I have done the following code that starts and ends with the same character but doesn't know how to specify it that the first char is from the specific set of character:
function regexVar() {
var re = /(.).*\1/
return re;
}
console.log("obcdo".test(s));
let suppose the specific set of chars is the vowel
(a, e, i, o, u)
in this case:
abcd ----> false
obcdo ----> true
ixyz ----> false
You need to use a character set to ensure the captured character is one of the ones you want, backreference the first captured group at the end of the pattern, not the third group (your pattern doesn't have 3 capture groups), use ^ and $ to anchor the pattern to the start and end of the string, and repeat with {2,} rather than * to make sure the whole string is at least 4 characters long:
/^([aeiou]).+\1$/
const re = /^([aeiou]).{2,}\1$/
console.log(
re.test('abcd'),
re.test('obcdo'),
re.test('ixyz')
);
You can use this pattern
/^([aeiou]).+\1$/i
^ - Start of string
([aeiou]) - Matches a,e,i,o,u any one of that. (group 1)
.+ - Match anything except new line.
\1 - Match group 1
$ - End of string
let startAndEnd = (str) =>{
return /^([aeiou]).+\1$/i.test(str)
}
console.log(startAndEnd(`ixyz`))
console.log(startAndEnd(`abcd`))
console.log(startAndEnd(`obcdo`))
If we are taking the set of vowels then,the regular expression for words beginning and ending with the same vowel is:
var re = /(\ba(\w+)a\b|\be(\w+)e\b|\bi(\w+)i\b|\bo(\w+)o\b|\bu(\w+)u\b)/g;
function regCheck(string){
let re = new RegExp(/^(a|e|i|o|u).*\1$/g);
return re.test(string);
}
regCheck('aewxyzae')

JS Regex: Remove anything (ONLY) after a word

I want to remove all of the symbols (The symbol depends on what I select at the time) after each word, without knowing what the word could be. But leave them in before each word.
A couple of examples:
!!hello! my! !!name!!! is !!bob!! should return...
!!hello my !!name is !!bob ; for !
and
$remove$ the$ targetted$# $$symbol$$# only $after$ a $word$ should return...
$remove the targetted# $$symbol# only $after a $word ; for $
You need to use capture groups and replace:
"!!hello! my! !!name!!! is !!bob!!".replace(/([a-zA-Z]+)(!+)/g, '$1');
Which works for your test string. To work for any generic character or group of characters:
var stripTrailing = trail => {
let regex = new RegExp(`([a-zA-Z0-9]+)(${trail}+)`, 'g');
return str => str.replace(regex, '$1');
};
Note that this fails on any characters that have meaning in a regular expression: []{}+*^$. etc. Escaping those programmatically is left as an exercise for the reader.
UPDATE
Per your comment I thought an explanation might help you, so:
First, there's no way in this case to replace only part of a match, you have to replace the entire match. So we need to find a pattern that matches, split it into the part we want to keep and the part we don't, and replace the whole match with the part of it we want to keep. So let's break up my regex above into multiple lines to see what's going on:
First we want to match any number of sequential alphanumeric characters, that would be the 'word' to strip the trailing symbol from:
( // denotes capturing group for the 'word'
[ // [] means 'match any character listed inside brackets'
a-z // list of alpha character a-z
A-Z // same as above but capitalized
0-9 // list of digits 0 to 9
]+ // plus means one or more times
)
The capturing group means we want to have access to just that part of the match.
Then we have another group
(
! // I used ES6's string interpolation to insert the arg here
+ // match that exclamation (or whatever) one or more times
)
Then we add the g flag so the replace will happen for every match in the target string, without the flag it returns after the first match. JavaScript provides a convenient shorthand for accessing the capturing groups in the form of automatically interpolated symbols, the '$1' above means 'insert contents of the first capture group here in this string'.
So, in the above, if you replaced '$1' with '$1$2' you'd see the same string you started with, if you did 'foo$2' you'd see foo in place of every word trailed by one or more !, etc.

How to replace semicolon except when encountering data uri specific text?

I am replacing all semicolons with line breaks but I have to make a few exceptions.
results = results.replace(/;/g, "\n");
But now I have 3 cases where I do not want to replace the semicolon:
data:image/png;
data:image/jpeg;
data:image/gif;
Basically any thing:
data:image/*;
I have tried:
results = results.replace(/^(data:image/png;)|;/g, "\n");
But it doesn't work.
This kind of works but it replaces the semicolon and one preceding character:
results = results.replace(/[^(data:image/png;)];/g, "\n");
Test data:
borderradius:10;borderradius:20;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQUAAAGQCAYAAACnPXVhAAAz9ElEQVR4Ae2d2a8VxdqH+QO44YaECxISQ0IICSGEEAghEoKBQEEbfXUX7JizwEBUFBUJAGPA0IChKEJwh59uR59rjrLIACO/pTGUgD0gAa+D+0cw+oAw0jjQAAAABJRU5ErkJggg==);
The [^(data:image/png;)]; contains a common user error: a character class (single character matching pattern) is used where a grouping construct (sequence
matching pattern) is meant to be used. See Regex expression not working with once or none for a similar issue.
You may use a regex capturing the data:image/[something]; and then use a callback to decide whether to keep the capture or replace the ; with a linebreak:
var s = "data:image/png; data/png; text";
var res = s.replace(/\b(data:image\/[^\/;]*;)|;/g, function (_, $1) {
return $1 ? $1 : "\n";
});
document.body.innerHTML = "<pre>" + res + "</pre>";
The /\b(data:image\/[^\/;]*;)|;/g will match multiple occurrences of:
\b(data:image\/[^\/;]*;) - Group 1 capturing a whole word data:image followed with /, then with zero or more characters other than / and ; up to the first ;
| - or..
; - a literal semicolon (just matched, no capturing group is used here)
In the callback, if $1 is set (not null), we restore the captured text with $1, and if not, we just replace with \n since we matched a "stray" ;.

Regex match lines that are not commented

So I have a string read from a JavaScript file, that will have:
...
require('some/path/to/file.less');
...
// require('some/path/to/file.less');
...
I'm using this reg-ex:
requireRegExp = /require(\ +)?\((\ +)?['"](.+)?['"](\ +)?\)\;?/g
To catch all those lines. However, I need to filter out the ones that are commented.
So when I run
while( match = requireRegExp.exec(str) ){
...
}
I will only get a match for the uncommented line that starts with require...
regequireRegExp = /^\s*require\('([^']+)'\);/gm
Explanation:
^ assert position at start of a line
\s* checks for a whitespace character 0 ... many times
require matches the word require
\( matches the character (
' matches the character '
([^']+)matches anything that isnt a ' 1 ... many times
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed
' matches the character ' literally
\) matches the character ) literally
; matches the character ; literally
g modifier: global. All matches (don't return on first match)
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
EDIT
Apparently you wanted to get the path in a group so I edited my answer to better respond to your question.
Here is the example:
https://regex101.com/r/kQ0lY8/3
If you want to match only those with require use the following:
/^\s*require.*/gm
See DEMO

JS regexp to match special characters

I'm trying to find a JavaScript regexp for this string: ![](). It needs to be an exact match, though, so:
`!()[]` // No match
hello!()[] // No match
!()[]hello // No Match
!()[] // Match
!()[] // Match (with a whitespace before and/or after)
I tried this: \b![]()\b. It works for words, like \bhello\b, but not for those characters.
The characters specified are control characters and need to be escaped also user \s if you want to match whitespace. Try the following
\s?!(?:\[\]\(\)|\(\)\[\])\s?
EDIT: Added a capture group to extract ![]() if needed
EDIT2: I missed that you wanted order independant for [] and () I've added it in this fiddle http://jsfiddle.net/MfFAd/3/
This matches your example:
\s*!\[\]\(\)\s*
Though the match also includes the spaces before and after !()[].
I think \b does not work here because ![]() is not a word. Check out this quote from MDN:
\b - Matches a word boundary. A word boundary matches the position where a word character is not followed or preceeded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.
Let's create a function for convenience :
function find(r, s) {
return (s.match(r) || []).slice(-1);
}
The following regular expression accepts only the searched string and whitespaces :
var r = /^\s*(!\[\]\(\))\s*$/;
find(r, '![]() '); // ["![]()"]
find(r, '!()[] '); // []
find(r, 'hello ![]()'); // []
This one searches a sub-string surrounded by whitespaces or string boundaries :
var r = /(?:^|\s)(!\[\]\(\))(?:\s|$)/;
find(r, '![]() '); // ["![]()"]
find(r, 'hello ![]()'); // ["![]()"]
find(r, 'hello![]()'); // []
To match all characters except letters and numbers you can use this regex
/[^A-Z0-9]/gi
g - search global [ mean whole text, not just first match ]
i -case insensitive
to remove any other sign for example . and ,
/[^A-Z0-9\.\,]/gi
In order to match exact string you need to group it and global parameter
/(\!\[\]\(\))/g
so it will search for all matches

Categories

Resources