Regex remove underscores from a given string - javascript

I try to transform string using String replace method and regular expression. How can I remove underscores in a given string?
let string = 'court_order_state'
string = string.replace(/_([a-z])/g, (_, match) => match.toUpperCase())
console.log(string)
Expected result:
COURT ORDER STATE

You could use JavaScript replace function, passing as input:
/_/g as searchvalue parameter (the g modifier is used to perform a global match, i.e. find all matches rather than stopping after the first one);
(blank space) as newvalue parameter.
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);

In your code you could match either and underscore or the start of the string (?:_|^) to also match the first word and match 1+ times a-z using a quantifier [a-z]+
Then append a space after each call toUpperCase.
let string = 'court_order_state';
string = string.replace(/(?:_|^)([a-z]+)/g, (m, g1) => g1.toUpperCase() + " ");
console.log(string)

let string = 'court_order_____state'
string = string.replace(/_+/g, ' ').toUpperCase()
console.log(string)

It can be as simple as the below:
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
Here the 'g' represents global, whereas the '/' is surrounded by what we're looking for.

Instead of matching the first character just after every _ and making them uppercase (from the regex that you have used), you can simply convert the entire string to uppercase, and replace the _ with space by the following:
let string = 'court_order_state';
string = string.toUpperCase().replace(/_+/g, " ");
console.log(string);

Related

String (double quote) formatting in Javascript

I have a string
var st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104"
Now I want to put a double quote around each substring
i.e required string
var st = ""asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104""
Is this possible to achieve anything like this in javascript?
If you meant to transform a string containing "words" separated by comma in a string with those same "words" wrapped by double quotes you might for example split the original string using .split(',') and than loop through the resulting array to compose the output string wrapping each item between quotes:
function transform(value){
const words = value.split(',');
let output = '';
for(word of words){
output += `"${word.trim()}", `;
}
output = output.slice(0, -2);
return output;
}
const st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104";
const output = transform(st);
console.log(output);
That's true unless you just meant to define a string literal containing a character that just needed to be escaped. In that case you had several ways like using single quotes for the string literal or backticks (but that's more suitable for template strings). Or just escape the \" inside your value if you are wrapping the literal with double quotes.
You can use backticks ``
var st = `"asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104"`
You can split the string by the comma and space, map each word to a quote-wrapped version of it and then join the result again:
const result = myString
.split(', ')
.map(word => `"${word}"`)
.join(', ')
Also you can transform your string with standard regular expressions:
// String
let st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv _ jkl4 _ 100x104";
// Use regular expressions to capture your pattern,
// which is based on comma separator or end of the line
st = st.replace(/(.+?)(,[\s+]*|$)/g, `"$1"$2`);
// Test result
console.log(st);

Remove part of the string before the FIRST dot with js

I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...

Need to replace a string from a long string in javascript

I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);

Splitting string but leave inner strings intact?

I have a string that looks like this 'a,b,"c,d",e,"f,g,h"'.
I would like to be able to split this string on , but leave encapsulated strings intact getting the following output : ["a","b","c,d","e","f,g,h"].
Is there a way to do this without having to parse the string char by char ?
You can create a match of the strings, then map the matches and replace any " in the elements:
let f = 'a,b"c,d",e,"f,g,h"';
let matches = f.match(/\w+|(["]).*?\1/g);
let res = matches.map(e => e.replace(/"/g, ''));
console.log(res);

Convert comma-separated string to nested array, RegExp?

Got this type of string:
var myString = '23, 13, (#752, #141), $, ASD, (#113, #146)';
I need to split it to an array with comma as separator but also converts (..) to an array.
This is the result I want: [23, 13, ['#752', '#141'], '$', 'ASD', ['#113', '#146']];
I got huge data-sets so its very important to make it as fast as possible. What's the fastest way? Do some trick RegExp function or do it manually with finding indexes etc.?
Here's a jsbin: https://jsbin.com/cilakewecu/edit?js,console
Convert the parens to brackets, quote the strings, then use JSON.parse:
JSON.parse('[' +
str.
replace(/\(/g, '[').
replace(/\)/g, ']').
replace(/#\d+|\w+/g, function(m) { return isNaN(m) ? '"' + m + '"' : m; })
+ ']')
> [23,13,["#752","#141"],"ASD",["#113","#146"]]
You can use RegEx
/\(([^()]+)\)|([^,()\s]+)/g
RegEx Explanation:
The RegEx contain two parts. First, to capture anything that is inside the parenthesis. Second, capture simple values (string, numbers)
\(([^()]+)\): Match anything that is inside the parenthesis.
\(: Match ( literal.
([^()]+): Match anything except ( and ) one or more number of times and add the matches in the first captured group.
\): Match ) literal.
|: OR condition in RegEx
([^,()\s]+): Match any character except , (comma), parenthesis ( and ) and space one or more number of times and add the match in the second captured group
Demo:
var myString = '23, 13, (#752, #141), ASD, (#113, #146)',
arr = [],
regex = /\(([^()]+)\)|([^,()\s]+)/g;
// While the string satisfies regex
while(match = regex.exec(myString)) {
// Check if the match is parenthesised string
// then
// split the string inside those parenthesis by comma and push it in array
// otherwise
// simply add the string in the array
arr.push(match[1] ? match[1].split(/\s*,\s*/) : match[2]);
}
console.log(arr);
document.body.innerHTML = '<pre>' + JSON.stringify(arr, 0, 4) + '</pre>'; // For demo purpose only
Just use the split method.
var str = '23, 13, (#752, #141), ASD, (#113, #146)',
newstr = str.replace(/\(/gi,'[').replace(/\)/gi,']'),
splitstr = newstr.split(',');

Categories