Not to match a pattern from a string - javascript

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

Related

How can get phrases from a string with regular expressions

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

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

Replace -84 in string: "my-name-is-dude-84" with '' by regex?

How to Replace -84 in a string: my-name-is-dude-84 with '' Regex?
I means the last '-' + number
I tried :
string = 'my-name-is-dude-84';
let regex = /[^\-*][1-9]/;
let specialChar = string.replace(regex, '');
then I received is my-name-is-dude-
I expect my string will be: my-name-is-dude
You're close, but this is what you need to do (I guess)
string = 'my-name-is-dude-84';
let regex = /-\d+$/;
let specialChar = string.replace(regex, '');
document.write(specialChar);
Your [^\-*] tries to match all characters but \, - and *. Also [1-9] only matches one digit (between 1 and 9). Use \d (all digits), and add a + to make it match one or more. Also, adding an end of string anchor $ to it makes it only match the hyphen+number at the end of the string.
You can use this regex (.*?)-\d+$
regex demo
JavaScript demo
string = 'my-name-is-99-dude-84';
let regex = /(.*?)-\d+$/;
let specialChar = string.replace(regex, "$1");
document.write(specialChar);

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

Replace first character of string

I have a string |0|0|0|0
but it needs to be 0|0|0|0
How do I replace the first character ('|') with (''). eg replace('|','')
(with JavaScript)
You can do exactly what you have :)
var string = "|0|0|0|0";
var newString = string.replace('|','');
alert(newString); // 0|0|0|0
You can see it working here, .replace() in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)
If you need to check if the first character is a pipe:
var string = "|0|0|0|0";
var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
alert(newString); // 0|0|0|0​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
You can see the result here
str.replace(/^\|/, "");
This will remove the first character if it's a |.
var newstring = oldstring.substring(1);
If you're not sure what the first character will be ( 0 or | ) then the following makes sense:
// CASE 1:
var str = '|0|0|0';
str.indexOf( '|' ) == 0 ? str = str.replace( '|', '' ) : str;
// str == '0|0|0'
// CASE 2:
var str = '0|0|0';
str.indexOf( '|' ) == 0? str = str.replace( '|', '' ) : str;
// str == '0|0|0'
Without the conditional check, str.replace will still remove the first occurrence of '|' even if it is not the first character in the string. This will give you undesired results in the case of CASE 2 ( str will be '00|0' ).
Try this:
var str = "|0|0|0|0";
str.replace(str.charAt(0), "");
Avoid using substr() as it's considered deprecated.
It literally is what you suggested.
"|0|0|0".replace('|', '')
returns "0|0|0"
"|0|0|0|0".split("").reverse().join("") //can also reverse the string => 0|0|0|0|

Categories