String split with different separators JavaScript [duplicate] - javascript

This question already has answers here:
Including a hyphen in a regex character bracket?
(6 answers)
Closed 3 years ago.
I am asking you how to split a string using different separators and when the string is empty return just an empty space.
I don't know to combine both.
All I have is:
function split(string) {
var str = string.split(/[+-*]/);
return str;
}
Example:
split("este-es+otro*ejemplo"); // => ["este", "es", "otro", "ejemplo"]
split(''); // => [""]
Thank you.

Move the * at the first position inside square bracket ([]).
If any special character, such as backslash (*) is immediately after the left square bracket, it doesn't have its special meaning and is considered to be one of the characters to match literally.
Try /[*+-]/g
function split(string) {
var str = string.split(/[*+-]/g);
return str;
}
console.log(split("este-es+otro*ejemplo"));

Related

How can I disallow a square bracket in a string when using regex to validate input text [duplicate]

This question already has answers here:
Difference between regex [A-z] and [a-zA-Z]
(6 answers)
Closed last month.
I want to disallow a string that has square brackets when using test method in regex.
function validateName(name){
var nameRegex = /^[A-zA-z\s][A-zA-z\s.-]{1,64}$/i;
console.log('##########Checking validation.........');
return nameRegex.test(name);
}
Try this regex and let me know:
/^[^\[\]]*$/
EDIT:
const regex = /^[^\[\]]*$/;
console.log(regex.test('ok')) // return true
console.log(regex.test('[ok')) // return false
console.log(regex.test('ok]')) // return false

Regex: split string by character except if inside quotes or double quotes [duplicate]

This question already has answers here:
Regex to match all instances not inside quotes
(4 answers)
Closed 2 years ago.
I need to split a string using a delimiter character (= in my example) , except if this character is inside quotes or double quotes
I succeed to do it within single quotes using \=+(?=(?:(?:[^']*'){2})*[^']*$) , or within double quotes using \=+(?=(?:(?:[^"]*"){2})*[^"]*$), but not for both, what would be the appropriate RegExp ?
Bonus: if it can also split when the character is not inside character ` , it would be perfect :)
What I need :
Edit: Javascript example to reproduce ( https://jsfiddle.net/cgnorhm0/ )
function splitByCharExceptInsideString(str, delimiterChar) {
// split line by character except when it is inside quotes
const escapedChar = delimiterChar.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
const regSplit = new RegExp(escapedChar + `+(?=(?:(?:[^']*'){2})*[^']*$)`);
const splits = str.split(regSplit);
return splits ;
}
const testStr = `image.inside {
sshagent(credentials: ['ssh-creds']) {
env.GIT_SSH_COMMAND="ssh -T -o StrictHostKeyChecking=no"
env.GIT_SSH_COMMAND2='ssh -T -o StrictHostKeyChecking=no'
}
}`;
const delimiterChar = '=';
const splitLs = splitByCharExceptInsideString(testStr,delimiterChar);
console.log(splitLs);
lookahead and lookbehind don't consume character so you can use multiple of them together. you can use
\=+(?=(?:(?:[^"]*"){2})*[^"]*$)(?=(?:(?:[^']*'){2})*[^']*$)(?=(?:(?:[^`]*`){2})*[^`]*$)
Regex Demo
The regex below finds = characters that are not inside `, ", or ' pairs.
const regex = /=(?=.*)(?=(?:'.*?'|".*?"|`.*?`).*?)/;
Behavior with your example:

Javascript Regex For only numbers and no white spaces [duplicate]

This question already has an answer here:
Why this javascript regex doesn't work?
(1 answer)
Closed 2 years ago.
I was very surprised that I didn't find this already on the internet.
is there's a regular expression that validates only digits in a string including those starting with 0 and not white spaces
here's the example I'm using
function ValidateNumber() {
var regExp = new RegExp("/^\d+$/");
var strNumber = "010099914934";
var isValid = regExp.test(strNumber);
return isValid;
}
but still the isValid value is set to false
You could use /^\d+$/.
That means:
^ string start
\d+ a digit, once or more times
$ string end
This way you force the match to only numbers from start to end of that string.
Example here: https://regex101.com/r/jP4sN1/1
jsFiddle here: https://jsfiddle.net/gvqzknwk/
Note:
If you are using the RegExp constructor you need to double escape the \ in the \d selector, so your string passed to the RegExp constructor must be "^\\d+$".
So your function could be:
function ValidateNumber(strNumber) {
var regExp = new RegExp("^\\d+$");
var isValid = regExp.test(strNumber); // or just: /^\d+$/.test(strNumber);
return isValid;
}

Replace '-' with '--' in a JavaScript string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I am trying to replace a single dash '-' character in a string with double dashes.
2015–09–01T16:00:00.000Z
to be
2015-–09-–01T16:00:00.000Z
This is the code I am using but it doesn't seem to be working:
var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.
In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.
For example,
var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');
Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to – and it is not the same as hyphen (-). The character codes for those characters are as follows
console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
The hyphen character – you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.
The correct RegExp in this case is temp.replace(/–/g,'--')
Probably the easiest thing would be to just use split and join.
var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");

How to include '\' character in a javascript string [duplicate]

This question already has answers here:
Escaping backslash in string - javascript
(5 answers)
Closed 8 years ago.
I'm trying to create a string in javascript which needs to be valid JSON the string is
{"query":"FOR u IN Countries RETURN {\"_key\":u._key}"}
I keep going around in circles as to how i can include the \ character given its also used to escape the quote character. can anyone help ?
Escape the backslash itself:
{"query":"FOR u IN Countries RETURN {\\\"_key\\\":u._key}"}
First pair of backslashes represents '\' symbol in the resulting string, and \" sequence represents a double quotation mark ('"').
Let JSON encoder do the job:
> s = 'FOR u IN Countries RETURN {"_key":u._key}'
"FOR u IN Countries RETURN {"_key":u._key}"
> JSON.stringify({query:s})
"{"query":"FOR u IN Countries RETURN {\"_key\":u._key}"}"
Use \\ for double quoted strings
i.e.
var s = "{\"query\":\"FOR u IN Countries RETURN {\\\"_key\\\":u._key}\"}";
Or use single quotes
var s = '{"query":"FOR u IN Countries RETURN {\"_key\":u._key}"}';

Categories