How to replace string using regex in javascript? - javascript

How to check a string and replace the space into "_" ?
let str = "hello #%123abc456:nokibul amin mezba jomadder% #%123abc456:nokibul% #%123abc456:nokibul amin mezba%"
str = str.replace(regex, 'something');
console.log(str);
// Output: str = "hello #%123abc456:nokibul_amin_mezba_jomadder% #%123abc456:nokibul% #%123abc456:nokibul_amin_mezba%"
Please help me out :)

Check this out. I think it's gonna help
Hints:
/:(\w+\s*)+/g Separates the :nokibul amin mezba jomadder as a group.
Replace the group with index-wise templating {0}, {1} ... {n}.
Mapping the groups. Ex: :nokibul amin mezba jomadder to :nokibul_amin_mezba_jomadder.
Finally, replacing the templates {index} with groups.
let str = "hello #%123abc456:nokibul amin mezba jomadder% #%123abc456:nokibul% #%123abc456:nokibul amin mezba%";
/* Extracting Groups */
let groups = str.match(/:(\w+\s*)+/g);
/* Formatting Groups: Replacing Whitespaces with _ */
let userTags = groups.map((tag, index) => {
/* Index wise string templating */
str = str.replace(tag, `{${index}}`)
return tag.replace(/\s+/g, "_");
});
console.log(str);
console.log(userTags);
/* Replacing string templates with group values */
userTags.forEach((tag, index) => str = str.replace(`{${index}}`, tag));
console.log(str);

Hint: You can use https://regex101.com/ to test whether a regex works, it supports substitution as well.
Regex being used: (\w+)[ ], to grep all words between space, and use $1_ to substitute the space to underscore.
const regex = /(\w+)[ ]/gm;
const str = `Input: str="nokibul" output: str="nokibul"
Input: str="nokibul amin" Output: str="nokibul_amin"
Input: str="nokibul amin mezba" Output: str="nokibul_amin_mezba"
Input: str="nokibul amin mezba jomadder" Output: str="nokibul_amin_mezba_jomadder"`;
const subst = `$1_`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

Simple one liner
str.replace(/:[^%]*%/g, arg => arg.replace(/ /g, '_'))
Explanation:
/:[^%]*%/g Find all occurrences starting with : and ending at %
This will return patterns like this :nokibul amin mezba jomadder% :nokibul% :nokibul amin mezba%
Next is to replace all space characters with underscores using this replace(/ /g, '_')

Related

Find and replace string text between two other string texts JS

I'm trying to find and replace a word in a string
Example:
let string =
`
Title: Hello World
Authors: Michael Dan
`
I need to find the Hellow World and replace with whatever I want, here is my attempt:
const replace = string.match(new RegExp("Title:" + "(.*)" + "Authors:")).replace("Test")
When you replace some text, it is not necessary to run String#match or RegExp#exec explicitly, String#replace does it under the hood.
You can use
let string = "\nTitle: Hello World\nAuthors: Michael Dan\n"
console.log(string.replace(/(Title:).*(?=\nAuthors:)/g, '$1 Test'));
The pattern matches
(Title:) - Group 1: Title: fixed string
.* - the rest of the line, any zero or more chars other than line break chars, CR and LF (we need to consume this text in order to remove it)
(?=\nAuthors:) - a positive lookahead that matches a location that is immediately followed with an LF char and Authors: string.
See the regex demo.
If there can be a CRLF line ending in your string, you will need to replace (?=\nAuthors:) with (?=\r?\nAuthors:) or (?=(?:\r\n?|\n)Authors:).
You might be better off converting to an object first and then just defining the title property:
let string =
`
Title: Hello World
Authors: Michael Dan
`
const stringLines = string.split('\n');
let stringAsObject = {};
stringLines.forEach(
(line) => {
if (line.includes(':')) {
stringAsObject[line.split(':')[0]] = line.split(':')[1];
}
}
);
stringAsObject.Title = 'NewValue';
You can use replace method like that:
string.replace("Hello World", "Test");
I can achieve this without regex. All you need is knowing the index of the string that you need to find.
var original = `
Title: Hello World
Authors: Michael Dan
`;
var stringToFind = "Hello World";
var indexOf = original.indexOf(stringToFind);
original = original.replace(original.substring(indexOf, indexOf + stringToFind.length), "Hey Universe!");
console.log(original)

Is there a way to remove a newline character within a string in an array?

I am trying to parse an array using Javascript given a string that's hyphenated.
- foo
- bar
I have gotten very close to figuring it out. I have trimmed it down to where I get the two items using this code.
const chunks = input.split(/\ ?\-\ ?/);
chunks = chunks.slice(1);
This would trim the previous input down to this.
["foo\n", "bar"]
I've tried many solutions to get the newline character out of the string regardless of the number of items in the array, but nothing worked out. It would be greatly appreciated if someone could help me solve this issue.
You could for example split, remove all the empty entries, and then trim each item to also remove all the leading and trailing whitespace characters including the newlines.
Note that you don't have to escape the space and the hyphen.
const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
.filter(Boolean)
.map(s => s.trim());
console.log(chunks);
Or the same approach removing only the newlines:
const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
.filter(Boolean)
.map(s => s.replace(/\r?\n|\r/g, ''));
console.log(chunks);
Instead of split, you might also use a match with a capture group:
^ ?- ?(.*)
The pattern matches:
^ Start of string
?- ? Match - between optional spaces
(.*) Capture group 1, match the rest of the line
const input = `- foo
- bar`;
const chunks = Array.from(input.matchAll(/^ ?- ?(.*)/gm), m => m[1]);
console.log(chunks);
You could loop over like so and remove the newline chars.
const data = ["foo\n", "bar"]
const res = data.map(str => str.replaceAll('\n', ''))
console.log(res)
Instead of trimming after the split. Split wisely and then map to replace unwanted string. No need to loop multiple times.
const str = ` - foo
- bar`;
let chunks = str.split("\n").map(s => s.replace(/^\W+/, ""));
console.log(chunks)
let chunks2 = str.split("\n").map(s => s.split(" ")[2]);
console.log(chunks2)
You could use regex match with:
Match prefix "- " but exclude from capture (?<=- ) and any number of character different of "\n" [^\n]*.
const str = `
- foo
- bar
`
console.log(str.match(/(?<=- )[^\n]*/g))
chunks.map((data) => {
data = data.replace(/(\r\n|\n|\r|\\n|\\r)/gm, "");
return data;
})
const str = ` - foo
- bar`;
const result = str.replace(/([\r\n|\n|\r])/gm, "")
console.log(result)
That should remove all kinds of line break in a string and after that you can perform other actions to get the expected result like.
const str = ` - foo
- bar`;
const result = str.replace(/([\r\n|\n|\r|^\s+])/gm, "")
console.log(result)
const actualResult = result.split('-')
actualResult.splice(0,1)
console.log(actualResult)

Javascript regex replace string on string

This regex removes all after match the pattern and i need to remove only the match pattern and the value.
pattern = /(?<=ANO=).*/
obj.where_str = " AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'"
obj.where_str = obj.where_str.replace(pattern, "'" + fieldValue + "'");
Thanks in advance
Method 1
My guess is that maybe you're trying to write an expression similar to:
\bANO='([^']*)'
The desired value to replace is in the capturing group:
([^']*)
RegEx Demo
const regex = /\bANO='([^']*)'/gm;
const str = ` AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'`;
const subst = `ANO='Another_value_goes_here'`;
const result = str.replace(regex, subst);
console.log(result);
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
And your code would probably look like:
const regex = /\bANO='([^']*)'/g;
const str = ` AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'`;
const fieldValue = 2020;
const subst = 'ANO=\''.concat(fieldValue, "'");
const result = str.replace(regex, subst);
console.log(result);
Method 2
Another option would likely be:
(?<=\bANO=')\d{4}
which I guess/assume that there would no problem with a positive lookbehind.
RegEx Demo 2
const regex = /(?<=\bANO=')\d{4}/g;
const str = ` AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'`;
const fieldValue = 2020;
const result = str.replace(regex, fieldValue);
console.log(result);

How to append a string to another string after every N char?

I am trying to create a program that adds "gav" after every second letter, when the string is written.
var string1 = "word"
Expected output:
wogavrdgav
You can use the modulus operator for this -
var string1 = "word";
function addGav(str){
var newStr = '';
var strArr = str.split('');
strArr.forEach(function(letter, index){
index % 2 == 1
? newStr += letter + 'gav'
: newStr += letter
})
return newStr;
}
console.log(addGav(string1)); // gives wogavrdgav
console.log(addGav('gavgrif')) //gives gagavvggavrigavf....
RegEx
Here, we can add a quantifier to . (which matches all chars except for new lines) and design an expression with one capturing group ($1):
(.{2})
Demo
JavaScript Demo
const regex = /(.{2})/gm;
const str = `AAAAAA`;
const subst = `$1bbb`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
RegEx Circuit
You can also visualize your expressions in jex.im:
If you wish to consider new lines as a char, then this expression would do that:
([\s\S]{2})
RegEx Demo
JavaScript Demo
const regex = /([\s\S]{2})/gm;
const str = `ABCDEF
GHIJK
LMNOP
QRSTU
VWXYZ
`;
const subst = `$1bbb`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Try this:
const string1 = 'word'
console.log('Input:', string1)
const newStr = string1.replace(/(?<=(^(.{2})+))/g, 'gav')
console.log('Output:', newStr)
.{2}: 2 any character
(.{2})+: match 2 4 6 8 any character
^(.{2})+: match 2 4 6 8 any character from start, if don't have ^, this regex will match from any position
?<=(regex_group): match something after regex_group
g: match all
This way is finding 2,4,6, etc character from the start of the string and don't match this group so it will match '' before 2,4,6, etc character and replace with 'gav'
Example with word:
match wo, word and ignore it, match something before that('') and replace with 'gav' with method replace

JS : Remove all strings which are starting with specific character

I have an array contains names. Some of them starting with a dot (.), and some of them have dot in the middle or elsewhere. I need to remove all names only starting with dot. I seek help for a better way in JavaScript.
var myarr = 'ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker';
var refinedArr = ??
You can use the filter function and you can access the first letter of every word using item[0]. You do need to split the string first.
var myarr = 'ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker'.split(", ");
var refinedArr = myarr.filter(function(item) {
return item[0] != "."
});
console.log(refinedArr)
Use filter and startsWith:
let myarr = ['ad', 'ghost', 'hg', '.hi', 'jk'];
let res = myarr.filter(e => ! e.startsWith('.'));
console.log(res);
You can use the RegEx \B\.\w+,? ? and replace with an empty String.
\B matches a non word char
\. matches a dot
\w+ matches one or more word char
,? matches 0 or 1 ,
[space]? matches 0 or 1 [space]
Demo:
const regex = /\B\.\w+,? ?/g;
const str = `ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

Categories

Resources