Strip specific characters and replaced with word [closed] - javascript

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 5 years ago.
Improve this question
If I have this string:
This string should #[1234] by another word
I want to replace to remove # [ ] and replace 1234 with 'test' word for example so the result is:
This string should test by another word
Is there any way to do this with js?

You can use regular expression to repalce your #[XXX] by test with the following code :
var string = "This string should #[1234] by another word";
console.log(string.replace(/#\[[0-9]+\]/gi, "test"));

I suggest to define a mapping from ids to replacements first.
Then you use string.replace(regex, callback) with a regex that matches #[1234] or any other id within the brackets and captures the id within a capture group.
Finally, you provide a callback which receives the value of the capture group as the second parameter and performs the replacement according to your mapping:
const input = 'This string should #[1234] by another word';
const replacements = {'1234': 'test'};
const output = input.replace(/#\[(\d+)\]/g, (match, id) => replacements[id]);
console.log(output);

I'm guessing you have multiple texts to replace? If so, you can use the String.replace function with a callback, which provides the replacement value. Something like this:
var repls = {
"1234": "test"
};
var text = "This string should #[1234] by another word";
var result = text.replace(/#\[([0-9]+)\]/g, function(entireMatch, key) {
return repls[key];
});
console.log(result);

Here's some code that doesn't use regular expressions, just split() and join(), and with strings as delimiters.
str='This string should #[1234] by another word';
console.log(str.split('#[1234]').join('test'));

Related

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)));

Remove all non numeric characters except first + operator [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 want to remove all non-numeric characters except the first + operator.
So + operator should show at the first.
For example,
+614a24569953 => +61424569953
+61424569953+ => +61424569953
Maybe,
(?!^\+)[^\d\r\n]+
replaced with an empty string would simply do that.
The first statement,
(?!^\+)
ignores the + at the beginning of the string, and the second one,
[^\d\r\n]+
ignores digits, newlines and carriage returns in the string.
RegEx Demo
Test
const regex = /(?!^\+)[^\d\r\n]+/g;
const str = `+614a24569953`;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
RegEx Circuit
jex.im visualizes regular expressions:
Try
t1="+614a24569953"
t2="+61424569953"
t3="6142+4569a9+53"
re = /(?<=\+.*)[^0-9]/g
console.log( t1.replace(re, '') );
console.log( t2.replace(re, '') );
console.log( t3.replace(re, '') );

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