How can get phrases from a string with regular expressions - javascript

How could I get from the string only the texts text_add () for_delete () this_edit ()
and leave them in an array.
I try to occupy a regular expression and filter by the data of the array and it doesn't work for me.
Who can help me?
let filter=["_add()","_delete()","_edit()"];
var cadena="text_add()-----for_delete()___ this_edit() this example is a test hello world";
var myMethod = new RegExp('(\\w*' + filter + '\\w*)', 'gi');
var matchesMethod = r.match(myMethod);
if (matchesMethod != null) {
arrayMethod.push(matchesMethod.toString().split(","));
}

try :
var cadena="text_add()-----for_delete()___ this_edit() this example is a test hello world";
var arr = cadena.match(/(\w*\(\))/g);
\w : Matches any word character (alphanumeric & underscore).
* : Match 0 or more characters.
\( : Matches a "(" character.
\) : Matches a ")" character.
g : global flag
here demo

Related

Getting the content between two characters

So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}

Not to match a pattern from a string

I am having the following string,
var str = "/\S\w\djoseph/";
I just wanted to fetch the characters that are not in the following pattern,
/\\(\w|\d)/
I mean I just want to extract joseph from the above string. I have tried with the following but my regex is not working as expected.
var str = "/\S\w\djoseph/";
var mat = /[^\\(\w|\d)]/g.exec(str);
console.log(mat); //["/"]
Can anyone help me to get the required string from the target string of mine?
You can use this regex in .replace with a callback:
/\S\whello\s\d/.source.replace(/(\\[wsd])|(.)/g, function($0, $1, $2){
return ($1 == undefined ? "" : $1) + ($2 != undefined ? $2.toUpperCase() : "");
})
//=> "\S\wHELLO\s\d"
This will uppercase anything that is not \w or \s or \d.
How about replacing everything that matches \. with the empty string?
var a = '\\a\\btest\\c\\d';
var result = a.replace(/\\./g, '');
console.log(result);

How do I delete all characters starting from a specific text on a string

The best way to explain this is by example. I'm using jQuery to do this.
Example I have a string
var str = "1.) Ben"
how can I dynamically omit the character 1.) including the space such that str === "Ben"
str can be dynamic such that order can increment from ones, tens, to hundreds.
E.G.
var str = "52.) Ken Bush"
or
var str = "182.) Hailey Quen"
Expected output
str === "Ken Bush"
or
str === "Hailey Quen"
Example
var str = "182.) Hailey Quen"
var test = str.split(') ');
test = test[1];
//output "Hailey Quen"
You can use regex replacement to get what you want.
var str = "182.) Hailey"
var newStr = str.replace(/^\d+\.\)\s*/, '')
// Hailey
var s = "1456.) Hard Spocker".replace(/^\d+\.\)\s*/, '')
// Hard Spocker
^ makes sure that the pattern is matched at the start of the string only
\d+ will match one or more digits.
\. will match the . with escaping
) is a symbol so we need to escape it using \ as \)
\s* will match one or more spaces.
You can learn about these symbols here.
Try using .substring() and .indexOf() as shown :-
var str = "182.) Hailey Quen"
alert(str.substring(str.indexOf(' ')))
DEMO
OR use .split() as shown :-
var str = "182.) Hailey Quen"
alert($.trim(str.split(')')[1]))
DEMO
You can do it regular expression,
var str = "52.) Ken".replace(/\d+\.\)\s/g,"");
console.log(str); //Ken
DEMO
If you have zero or more than zero spaces after the ) symbol then you can use *,
var str = "52.) Ken".replace(/\d+\.\)\s*/g,"");
console.log(str); //Ken
Dismantling regex used,
/ states regex left border
\d d states normal character d, if we want to make it match
numbers then we have to escape it with \
+ It states that one or more number should be there.
\. Again . is a metacharacter to match any valid character, so
escape it.
\) Parenthesis is also a metacharacter to close a group, escape
it.
\s* 12.) can be followed by zero or more spaces.
/ states regex right boundary.
g global flag, which used to do a search recursively.
You can do it like this
var testURL = "182.) Hailey Quen";
var output = testURL.substring(testURL.lastIndexOf(")") + 1).trim();
console.log(output);
*trim function will help to remove extra space if any.Hope it will help

regex to remove number (year only) from string

I know the regex that separates two words as following:
input:
'WonderWorld'
output:
'Wonder World'
"WonderWorld".replace(/([A-Z])/g, ' $1');
Now I am looking to remove number in year format from string, what changes should be done in the above code to get:
input
'WonderWorld 2016'
output
'Wonder World'
You can match the location before an uppercase letter (but excluding the beginning of a line) with \B(?=[A-Z]) and match the trailing spaces if any with 4 digits right before the end (\s*\b\d{4}\b). In a callback, check if the match is not empty, and replace accordingly. If a match is empty, we matched the location before an uppercase letter (=> replace with a space) and if not, we matched the year at the end (=> replace with empty string). The four digit chunks are only matched as whole words due to the \b word boundaries around the \d{4}.
var re = /\B(?=[A-Z])|\s*\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match) {
return match ? "" : " ";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
A similar approach, just a different pattern for matching glued words (might turn out more reliable):
var re = /([a-z])(?=[A-Z])|\s*\b\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match, group1) {
return group1 ? group1 + " " : "";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
Here, ([a-z])(?=[A-Z]) matches and captures into Group 1 a lowercase letter that is followed with an uppercase one, and inside the callback, we check if Group 1 matched (with group1 ?). If it matched, we return the group1 + a space. If not, we matched the year at the end, and remove it.
Try this:
"WonderWorld 2016".replace(/([A-Z])|\b[0-9]{4}\b/g, ' $1')
How about this, a single regex to do what you want:
"WonderWorld 2016".replace(/([A-Z][a-z]+)([A-Z].*)\s.*/g, '$1 $2');
"Wonder World"
get everything apart from digits and spaces.
re-code of #Wiktor Stribiżew's solution:
str can be any "WonderWorld 2016" | "OneTwo 1000 ThreeFour" | "Ruby 1999 IamOnline"
str.replace(/([a-z])(?=[A-Z])|\s*\d{4}\b/g, function(m, g) {
return g ? g + " " : "";
});
import re
remove_year_regex = re.compile(r"[0-9]{4}")
Test regex expression here

Javascript Regex - Replace all occurences of matching string EXCEPT any string between brackets

I need to replace a string that has has instances inside another but ignore replacing any string if it is inside curly braces.
I have tried the following:
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "%")
// % % test %%
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "$1"+"%")
// replace% % test replaces%replace%
But I need the replace to look like this: "% {replace} test %%"
Can anyone suggest how to do this inside Javascript?
You can use a function with String.replace(). If capture is found, braced stuff is returned, else %.
var str = "replace {replace} test replacesreplace";
str = str.replace(/({[^}]*})|replaces?/g, function($0, $1) {
return typeof $1 != 'undefined' ? $1 : "%";
});
document.write(str);
Use Negative lookahead
Regex Demo
(?!\{)replace(?!\})
(?!\{): Negative Lookahead - Assert that it is impossible to match { literal
replace: Matches replace string literally
(?!\}): Negative Lookahead - Assert that it is impossible to match } literal
Javascript Demo
var str = "replace {replace} test replacesreplace";
var replacedStr = str.replace(/(?!\{)replace(?!\})/g, "%");
document.write(replacedStr);

Categories