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.
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 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 );
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))
I want to after type Title of post automatically take value and create slug. My code works fine with English Latin characters but problem is when I type characters 'čćšđž'. Code replace first type of this characters in string but if character is repeated than is a problem. So, for testing purpose this title 'šžđčćžđš čćšđžčćšđž čćšđžčć ćčšđžšžčćšđ ćčšžčć' is converted to this slug 'szdcc'.
This is my jquery code:
$('input[name=title]').on('blur', function() {
var slugElement = $('input[name=slug]');
if(slugElement.val()) {
return;
}
slugElement.val(this.value.toLowerCase().replace('ž', 'z').replace('č','c').replace('š', 's').replace('ć', 'c').replace('đ', 'd').replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, ''));
});
How to solve this problems? Also is it possible to this few characters put in same replace() function?
Try this:
function clearText(inp) {
var wrong = 'čćšđž';
var right = 'ccsdz';
var re = new RegExp('[' + wrong + ']', 'ig');
return inp.replace(re, function (m) { return right.charAt(wrong.indexOf(m)); });
}
replace() only replaces the first occurrence unless regex is used with global modifier. You will need to change them all to regular expression.
replace(/ž/g, "z")
As far as I know, it will not be possible to use a single replace() in your case.
If you are concerned with chaining a bunch of .replace() together, you might be better off writing some custom code to replace these characters.
var newStr = "";
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
switch (c) {
case "ž": newStr += "z"; break;
default: newStr += c; break;
}
}
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I've looked up this question but am new to coding so I'm not quite able to relate other answers to this.
Given a string s, return a string
where all occurrences of its first char have
been changed to '*', except do not change
the first char itself.
e.g. 'babble' yields 'ba**le'
Assume that the string is length 1 or more.
Hint: s.replace(stra, strb) returns a version of string s
where all instances of stra have been replaced by strb.
This is what I have, but this does not replace every character after except the first, it just replaces the next character.
function fixStart(s)
{
var c = s.charAt(0);
return c + s.slice(1).replace(c, '*');
}
function fixStart(s) {
var c = s.charAt(0);
var outputStr = '';
// literate through the entire string pushing letters into a new string unless it is the first letter
for (var i = 0; i < s.length; i++) {
// if the letter is the first letter AND we are not checking the first letter
if (s[i] === c && i !== 0) outputStr += '*'
else outputStr += s[i]
}
return outputStr;
}
console.log(fixStart('hellohahaha'))
To replace all occurrences not just the first, you can use a RegExp:
function fixStart(s) {
var c = s.charAt(0);
return c + s.slice(1).replace(new RegExp(c, 'g'), '*');
}
For example if the value of c is "b", then new RegExp(c, 'g') is equivalent to /b/g.
This will work for simple strings like "babble" in your example. If the string may start with special symbols that mean something in regex, for example '.', then you will need to escape it, as #Oriol pointed out in a comment. See how it's done in this other answer.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am trying to write a string or integer formula which will look a code between parentheses.My logic is this: Search for the first parentheses, find the last parentheses, and return everything in between. Im sure there is a string or integer function, but not exactly sure which one will do the trick. And by the way, the code in between the parentheses varies from length 3 to 9.kindly check this code enter code here
var n;
var $;
var str = document.getElementById("demo").innerHTML;
var p = str.indexOf(")");
var q = str.indexOf("(");
var res = str.replace(")", "");
var re = str.replace("(", "");
document.getElementById("demo").innerHTML = res;
var k = str.replace("$", "(" + "$")
.replace(/,$/, ".")
.replace(")", "(" + res + ")")
.replace("(", "(" + res + ")")
.replace(/O/g, 0)
.replace(/o/g, 0)
.replace(/g/g, 9)
.replace(/\s/g, "");
document.getElementById("demo3").innerHTML = k;
From what I can understand of your question, you just want to search a string of anything and pull out the characters that are surrounded by paranthesis. This is very easy.
var foo = 'blah(capture this)blah';
var result = foo.match(/\(([^()]+)\)/);
//this simply says: capture any characters surrounded by paranthesis, as long as there is at least one character.
console.log(result[1]);
Update based on your comments:
The logic is very easy to follow.
var regex = new RegExp(
'\\(?'+ //optional (
'\\$?'+ //optional $
'(\\d+)' //capture any digit, at least one
);
function format(userInput) {
var results = userInput.match(regex);
if (results === null) { results = [0,0]; }
//get the important part (the digits), format it however you want.
var formatted = '($'+results[1]+'.00)';
return formatted;
}
//all output ($1234.00)
console.log(format('$1234)'));
console.log(format('($1234.00'));
console.log(format('1234'));
console.log(format('1234.0'));
console.log(format('1234)'));
console.log(format('(1234.0'));