Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
here is my simple question
const str = _world.(hello)+=.is..to.#%smart+/
can anyone give regex expression for this
output
onlyDots avoid all content
onlyDots = '....'
You can split the string & then filter the dot characters & finally join them back!
const str = "_world.(hello)+=.is..to.#%smart+/";
const result = str.split("").filter(k => k === ".").join("");
console.log(result);
You can simply the count the occurrences of . in the string.
const str = "_world.(hello)+=.is..to.#%smart+/"
let dotCount = 0;
for (let s of str) {
if (s === ".") {
dotCount += 1
}
};
const result = ".".repeat(dotCount);
console.log(result);
If you want to use Regex then you can simply replace all non dot characters into empty string.
const str = "_world.(hello)+=.is..to.#%smart+/"
const res = str.replaceAll(/[^.]/g, "");
console.log(res);
Something like this should work.
const str = "_world.(hello)+=.is..to.#%smart+/";
console.log(str.replace(/[a-zA-Z 0-9!##\$%\^\&*\)\(+='_/-]/g, "."));
To do this in regex you can match all characters that are not a dot, and replace with an empty string:
const str = "_world.(hello)+=.is..to.#%smart+/";
const dots = str.replace(/[^.]/g, "");
console.log(dots); // expected output: .....
First make the following corrections in order to turn your code into valid code:
Enclose the right-hand side in "" so it is a valid string
Then, use String#replace and a regex that can replace more than one non-dot character at a time as follows:
const str = "_world.(hello)+=.is..to.#%smart+/",
output = str.replace(/[^\.]+/g, '');
console.log( output );
Alternatively, you can pass a function to the String#replace method as follows:
const str = "_world.(hello)+=.is..to.#%smart+/",
output = str.replace(/./g, c => c === "." ? "." : "");
console.log( output );
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have this string that I would like to split into an array
string = "2009C20402052C3200C3360C22503201C"
This is how I would like it to split.
result = ["2009C", "2040", "2052C", "3200C", "3360B", "2250", "3201C"]
Basically I would like to know how to split it, if there are 4 digits on their own or 4 digits followed by a C (5 characters in total). How can I do that?
If you want to split into groups of four digits followed by a C (five characters in total), or just four digits if the C isn't there, you can do it like this:
const rex = /\d{4}C?/g;
let match;
const parts = [];
while ((match = rex.exec(string)) !== null) {
parts.push(match[1]);
}
The regular expression is \d{4} (four digits) and C? (optional C).
Live Example
const string = "2009C20402052C3200C3360C22503201C";
const rex = /\d{4}C?/g;
let match;
const parts = [];
while ((match = rex.exec(string)) !== null) {
parts.push(match[0]);
}
console.log(parts);
Or if you like you can do it while hiding the loop in the replace and split functions (the loop is still there — two of them, actually —just not in your code):
const parts = string.replace(/\d{4}C?/g, "$&\n")
.trim().split("\n")
Live Example:
const string = "2009C20402052C3200C3360C22503201C";
const parts = string.replace(/\d{4}C?/g, "$&\n")
.trim().split("\n")
console.log(parts);
One trick which seems to be working is to replace every four digit number with that same number preceded by space. Then, trim that string, and split on single space.
var string = "2009C20402052C3200C3360C22503201C"
var parts = string.replace(/(\d{4})/g, " $1").trim().split(" ");
console.log(parts);
This question already has answers here:
Remove string after predefined string
(4 answers)
Closed 4 years ago.
I had a sentence like this 'someurl.com/?something=1,2,3' i want to check if the char had something= then remove all character after that.
so like this.
'soome.url/?something=1,2,3,1' => 'soome.url/?'
'soome.url/nothing?nothingtoo?something=1,2,3,1' => 'soome.url/nothing?nothingtoo?'
'soome.url/nothing?something=1,2,3,1' => 'soome.url/nothing?'
how to do that in Javascript?
There are already other pretty good answers with split method.
If you still want to know how to do it with regex
let arr = [`soome.url/?something=1,2,3,1'`
,`soome.url/nothing?nothingtoo?something=1,2,3,1`,
`soome.url/nothing?something=1,2,3,1`]
arr.forEach(e=>{
console.log(e.replace(/\?(?:something=.*)$/g,'?'))
})
Using split and getting the first index will return the string before something=.
const urlOne = 'soome.url/?something=1,2,3,1' // 'soome.url/?'
const urlTwo = 'soome.url/nothing?nothingtoo?something=1,2,3,1' // 'soome.url/nothing?nothingtoo?'
const urlThree = 'soome.url/nothing?something=1,2,3,1' // 'soome.url/nothing?'
function strip(url){
return url.split('something=')[0];
}
console.log(strip(urlOne));
console.log(strip(urlTwo));
console.log(strip(urlThree));
Assuming it's always the last parameter, you could just split the url at something:
const url = 'soome.url/nothing?nothingtoo?something=1,2,3,1';
const newUrl = url.split("something")[0]
console.log(newUrl)
You can also try like following using substr.
let url1 = "soome.url/nothing?nothingtoo?something=1,2,3,1";
let pattern = "something=";
let str2 = url1.substr(0, url1.indexOf(pattern) <= 0 ? str1.length : url1.indexOf(pattern));
console.log(str2);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I would like to know how to split and get the values in the following variable
var str= "send-money-from-united-states-to-hong-kong"
var str1= "send-money-from-thailand-to-singapore"
Expected Output: United States Hong Kong
Expected Output: Thailand Singapore
No need for regular expression here.
This simple code will extract wanted data:
var strArr = "send-money-from-thailand-to-singapore".replace("send-money-from-", "").split("-");
for (i = 0; i < strArr.length; i++) {
// capitalize letters
strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1);
}
var countries = strArr.join(" ").split(" To ");
console.log(countries[0]);
console.log(countries[1]);
I assumed that strings are in the same format: starting with send-money-from- and countries are divided by -to-.
Solved by the following js.
Could be simplified, but made it stepwise for better understading:
var str = "send-money-from-united-states-to-hong-kong"
str = str.replace("send-money-from-", "");
str = str.replace("-to-", " ");
str = str.replace(/-/g, " ");
str = str.split(" ");
for (i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1)
}
console.log(str.join(" "));
Using the split function from javascript will help
var strArr = str.split('-')
You'll get an array that you can then manipulate to your liking. So for your expected output you'll want to concatenate the indexes that you require.
var strArr = str.split('-')
var strArr2 = str2.split('-')
console.log(strArr[4], strArr[5], strArr[6], strArr[7])
console.log(strArr2[3], strArr2[5])
Then using a custom function, you can get a title
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
strArr[2].toProperCase()
Lodash can make this manipulation minimized such as:
var strArr = _.map(_.split(str), function(text) { return _.startCase(text) })
And then get the necessary values. In terms of manipulating the array to get the correct values from the string, you will need some sort of template array that has the text that you will accept.
Then you can map through the string array against that template array and only accept the values that fulfill a true condition.
// Remember evaluating case when creating array (LowerCase vs TitleCase)
var templateArray = ['Thailand', 'Singapore']
var strArr = _.map(_.split(str), function(text) { return _.startCase(text) })
var reducer = function(accumulator, currentValue) {
if(templateArray.includes(currentValue)) {
accumulator.push(currentValue)
}
}
var newString = strArr.reduce(reducer, [])
This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Closed 6 years ago.
I have the following string
str = "11122+3434"
I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *
I have tried the following
strArr = str.split(/[+,-,*,/]/g)
But I get
strArr = [11122, 3434]
Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.
In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).
For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:
var result = str.match(/(\d+)([+,-,*,/])(\d+)/);
returns an array:
["11122+3434", "11122", "+", "3434"]
So your values would be result[1], result[2] and result[3].
This should help...
str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)
Hmm, one way is to add a space as delimiter first.
// yes,it will be better to use regex for this too
str = str.replace("+", " + ");
Then split em
strArr = str.split(" ");
and it will return your array
["11122", "+", "3434"]
in bracket +-* need escape, so
strArr = str.split(/[\+\-\*/]/g)
var str = "11122+77-3434";
function getExpression(str) {
var temp = str.split('');
var part = '';
var result = []
for (var i = 0; i < temp.length; i++) {
if (temp[i].match(/\d/) && part.match(/\d/g)) {
part += temp[i];
} else {
result.push(part);
part = temp[i]
}
if (i === temp.length - 1) { //last item
result.push(part);
part = '';
}
}
return result;
}
console.log(getExpression(str))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can I wrap a string in parantheses that has another random value in it? Look at this for explaining better to understand:
var str = "ss(X)+ss(X)"
INTO:
"(ss(X))+(ss(X))"
NOTE: X can be any value like: "223" or "abc" "2+2+2"
If the string is random data, then this would be impossible, since you don't know what you actually want wrapped. Step 1: find out the condition for "this should be wrapped" versus "this should not be wrapped". We can then do a simple replacement:
var shouldbewrapped = /([a-zA-Z\(\)])+/g;
var wrapped = string.replace(shouldbewrapped, function(found) {
return "(" + found + ")";
});
This does a regexp replace, but instead of replacing a string with a string, it replaces a string with the output of a function run on that string.
(note that the 'g' is crucial, because it makes the replace apply to all matches in your string, instead of stopping after running one replacement)
You can try this:
str = str.replace(/\w*\(\d*\)/g, function () {return '(' + arguments[0] + ')';});
A live demo at jsFiddle
EDIT
Since you've changed the conditions, the task can't be done by Regular Expressions. I've put an example, how you can do this, at jsFiddle. As a side effect, this snippet also detects possible odd brackets.
function addBrackets (string) {
var str = '(' + string,
n, temp = ['('], ops = 0, cls;
str = str.replace(/ /g, '');
arr = str.split('');
for (n = 1; n < arr.length; n++) {
temp.push(arr[n]);
if (arr[n] === '(') {
ops = 1;
while (ops) {
n++;
temp.push(arr[n]);
if (!arr[n]) {
alert('Odd opening bracket found.');
return null;
}
if (arr[n] === '(') {
ops += 1;
}
if (arr[n] === ')') {
ops -= 1;
}
}
temp.push(')');
n += 1;
temp.push(arr[n]);
temp.push('(');
}
}
temp.length = temp.length - 2;
str = temp.join('');
ops = str.split('(');
cls = str.split(')');
if (ops.length === cls.length) {
return str;
} else {
alert('Odd closing bracket found.');
return null;
}
}
Just as a sidenote: If there's a random string within parentheses, like ss(a+b) or cc(c*3-2), it can't be matched by any regular pattern. If you try to use .* special characters to detect some text (with unknown length) within brackets, it fails, since this matches also ), and all the rest of the string too...
I think your going to need to do some string interpolation. Then you can set up some Math.random or whatever you want to generate randomness with.