Replace method in javascript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to replace a string in javascript using regex but not able to do it. What I am trying is:
var str = [{"Contact":["{"name":"abc","address": "xyz","PhoneNumber": "08976"}", "{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]
str.replace(/"\\{/g,"\\{") // replace every instance of "{ with just {
I want to replace all instance of "{ with just { and all instance of }" with just }. How can I do 2 replacement together and where I am going wrong in 1 replacement as the replacement that I am using is not actually happening.

Escape { with \ once. Escaping in the replacement string is not necessary.
str.replace(/"\{/g,"{")
// "[{"Contact":[{"name":"abc","address": "xyz","PhoneNumber": "08976"}", {"name":"abc","address": "xyz","PhoneNumber": "08976"}",{"name":"abc","address": "xyz","PhoneNumber": "08976"}",{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]"
BTW, str in the question is not a string literal.

You can do both replacement in single replace call:
var repl = str.replace(/"(\{)|(\})"/g, '$1$2');
Make sure str is a valid string
You can use built-in JSON parsing to avoid use of regex

If you meant the string to be an actual string...
// Be sure that it's a string
var str = '[{"Contact":["{"name":"abc","address": "xyz","PhoneNumber": "08976"}", "{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]';
// Assign the output to a variable and use single backslash to escape `{`. You're
// using the literal regex construct here / ... /
result = str.replace(/"(\{)|(\})"/g,"$1$2");
And to replace both "{ to { and }" to }, you can use capture groups, backreferences and an "or" regex operator (|).
jsfiddle

Related

Regex, how to detect value in double curly braces? [closed]

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
Sorry i can't speak english :(
I write Supplant I have a regex
({{([']).*\2}})
needs regex to detect what is in a rectangle
I need it rigidly between {{' - '}} because there can be any character between the quotation marks (e.g. one { )
best to use it \1 because regex is more longer
Thanks for the help. Regards
This can work for you:
/\{\{'((?:(?!\{\{').)*?)'\}\}/g
\{\{' - start by matching {{'.
( ... ) - if you're writing a template engine you probably care about what's inside the curly braces and quotes. This captures the string inside the quotes so you'll be able to use it.
(?: ... ) - a non-captureing group (the value here will not be used).
(?!\{\{'). - match anything, except if we're seeing another {{'.
(?!\{\{').)*? - *? is a lazy match, so we'll stop at the first '}}
and finally, the closing '}}
as code it will looks something like this - I included a function to set the replaced value, because typically that's what you'd do in a template engine:
let s = "n {{'a{123456789}'}} n {{\"a{123456789}\"}} n {{'a{1234{{'a{12345{{'a{123456789}'}}6789}'}}56789}'}} ";
s = s.replace(/\{\{'((?:(?!\{\{').)*?)'\}\}/g, (wholeMatch, capturedKey) => {
console.log('captured key:', capturedKey);
return "REPLACED " + capturedKey;
});
console.log(s);
if you want to support double quotes it becomes a bit more complicated:
s = s.replace(/\{\{(["'])((?:(?!\{\{["']).)*?)\1\}\}/g,
(wholeMatch, quote, capturedKey) => { ... }
);
Try this:/(?<={{')(?!.+?{{)[^']+/gm
This basically looks for the {{' which doesn't have any other {{ in front of it then, matches everything till the first '.
Test here: https://regex101.com/r/rw6kkP/2
var myString = `{{'a{content 1}a'}}
{{'a{every{{'a{everysign}a'}}sign}a'}}
{{'a{every{{'a{every{{'a{inside content}a'}}sign}a'}}sign}a'}} `;
var myRegexp = /(?<={{')(?!.+?{{)[^']+/gm;
console.log(myString.match(myRegexp))
// [ "a{content 1}a", "a{everysign}a", "a{inside content}a" ]

How to match numbers followed by any combination of special characters and spaces using regex [closed]

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 last year.
Improve this question
I am a newbie with regex and I am having trouble trying to match some parts of a string so I can remove it from a piece of entered text. I want to match digits followed by a sequence of a combination of any special characters + spaces. There could also be non Latin characters that should not be removed inside the sequence (for example Ñ).
for example inputted it may look like:
11#- &-.text
11 $ab*cÑ .somewords123
outputted I would expect
text
abcÑsomewrods123
I am using javascript replaceall method with regex to find it. So far I have something basic like this regex
.replaceAll(/\d+(\#|\s)+(\-|\$)+(\s|\&)+(\&)+(\-)+(\.)/g, '');
Is there a way to write this more efficiently so that it captures any special characters since the text can contain more different special chars than in the examples? Or is this a situation better handled with pure JS?
Thanks in advance for your help.
You should ether have blacklist of what you calling special characters, or whitelist of the allowed characters.
for blacklist it gonna look like:
const blacklist = "!##$%^&*()_+.";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[${blacklist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));
for whitelist it gonna looks like:
const whitelist = "0-9a-zA-Z";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[^${whitelist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));

Javascript Array - Split string at numbers [closed]

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 have an unknown string containing a set of numbers like so:
var string = "stuff 1.23! (456) 789 stuff";
I would like to split the array, in order to modify the numbers and later rejoin the array. The result I'm looking for should look like this:
var result = ['stuff ', 1.23, '! (', 456, ') ', 789, ' stuff'];
Is there a better solution than to loop through each character individually? Thanks!
use a character class to split the values:
/(-?[\d.]+)/
-? May start with a negative such as -123
[\d.]+ Has one or more numbers and decimals
var string = "stuff 1.23! (456) 789 stuff -234".split(/(-?[\d.]+)/);
console.log(string)
The ideal solution really depends on what exactly you are doing with the data. One simple solution is a regular expression with replace.
var string = "stuff 1.23! (456) 789 stuff";
var updated = string.replace(/\d+(\.\d+)?/g, function (m) {
console.log(m);
return "xxx";
})
console.log(updated)
A regular expression is an expression you can use to search within your string, in you case, for digits. Create a regular expression which searches for sequences of digits, and you'll be able to use the split method on your string to create an array of strings like you specified.

split a string with comma and colon [closed]

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 6 years ago.
Improve this question
I have a string like as shown below:
var String = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"
Where xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx represents an alphanumeric generated Id and after the colon is a string related to that Id.The string can be a string with comma or without comma.What I wanted was that I wanted to split the string such that I get an array with ID:its corresponding string , just like shown below.
["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma",
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"]
HOW I ACCOMPLISHED THIS
I used the javascript split function where i split the string by comma followed by 36 characters (for ID) and colon.
String.split(/,(?=.{36}:)/);
PS: I apologize as previously I was not able to ask the question in the correct manner.Hope this time people understand it.
You could use String#split by comma and a look ahead for numbers and colon.
var x = "123456:a,b,c,435213:r,567876:e,363464:t,y,u";
array = x.split(/,(?=\d+:)/);
console.log(array);
For alphanumeric values
var x = "1A3456:a,b,c,43Y213:r,567W76:e,363x64:t,y,u";
array = x.split(/,(?=[a-z0-9]+:)/i);
console.log(array);
You can use the method .split(). I used the "$" as a split sign instead of "," because i thought you would like to keep them.
var values = "123456:a,b,c$435213:r$567876:e$363464:t,y,u".split("$");
var x = values[0];
console.log(values)

Get all values between '[ ]' on a string with JavaScript [closed]

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 8 years ago.
Improve this question
How are you guys doing?
I'd like to ask today if you could help me with a tricky question that I was unable to solve on my own.
I [have] strings that [are] like this.
I was looking for a way to get "have" and "are" and form an array with them using JavaScript. Please notice that this is an example. Sometimes I have several substrings between braces, sometimes I don't have braces at all on my strings.
My attempts focused mostly on using .split method and regex to accomplish it, but the closest I got to success was being able to extract the first value only.
Would any of you be so kind and lend me an aid on that?
I tried using the following.
.split(/[[]]/);
You can use the exec() method in a loop, pushing the match result of the captured group to the results array. If the string has no square brackets, you will get an empty matches array [] returned.
var str = 'I [have] strings that [are] like this.'
var re = /\[([^\]]*)]/g,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
}
console.log(matches) //=> [ 'have', 'are' ]
Note: This will only work correctly if the brackets are balanced, will not perform on nested brackets.
var str = "I [have] strings that [are] like this";
var res = str.split(" ");
The result of res will be an array with the values:
I
[have]
strings
that
[are]
like
this
If you want to get only values between braces, you can use the following regex expression:
var str = "I [have] strings that [are] like this";
var result = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((result = pattern.exec(str)) != null)
{
result.push(match[1]);
}
This is JSFiddle example for you.
Simple as this:
'I [have] strings that [are] like this.'.match(/\[([^\]]*)]/g)

Categories

Resources