How to replace matched characters with a same number of spaces - javascript

I am using javascript and looking for a regex which can replace a matched string with the same number of space. For example, I want to match a string which begins with show and ends to the end of line, this is the regex I am using /show .*$/. If users type show dbs then I want to replace with (8 spaces). How can I know the number of characters for the matched string?

I believe the most concise way to achieve such results in javascript with RegEx is to match one part of the string, replace the rest with spaces and concatenate both parts as follows:
str.replace(/^(show)(.*)/, (str, p1, p2) => p1 + p2.replace(/./g, " "));
The first replace will separate the beginning from the end and send those parts as arguments into the method. The first part can be left untouched and the second part transformed into spaces.

you can use .length on the matched element. For example
var pat = /show .*$/
'show dbs'.match(pat)[0].length
will return 8 then you can either concatenate the returned value or use .replace() on it
'show dbs'.replace(/^/, " ".repeat(8)) //we got 8 from the length property
Note: if there are multiple matches you'll have to loop over them

Related

Extract text from document title

I try to extract all text from document title before it gets to closest "|" or "-" or "/" . I assume i have to write something like this but im not good at regex.
var docTitle = document.title();
docTitle.match(regex);
Can someone help me with correct regex or suggest perhaps a better solution to achieve desired effect ?
Thank you !
Use var shortTitle = document.title.split(/[|\/-]/,1)[0];
The split function divides a string into an array based on a separator.
You can pass a Regular Expression object into the split function if the separator is a pattern and not constant.
The regular expression is [|/-] meaning any |, /, or -. The / needed to be escaped with a \ in JavaScript because / is also the character that delimits Regular Expression literals.
The first element of the split array ([0]) will be the document title before the first occurrence of any of those separator characters.
It will be the only element in the array, because we told the split function to stop after the first occurrence.
If the document title contains no matching characters to split on, the split function returns the whole string in the first array element, anyway.

Regex get inconsistent length of string's value

2f34435-something.jpg
4t44234-something.jpg
5465g67-something.jpg
says I have 3 string above, without using split, how can I do regex to get the value before dash? the length of strings is not consistent though..
One option would be to match one or more non-dash characters at the beginning of the string:
^[^-]+
^ - Anchor that denotes the beginning of the string
[^-] - Character set to match all characters that are not dashes.
+ - One or more occurrences of non-dash characters.
For instance:
'2f34435-something.jpg'.match(/^[^-]+/);
// ["2f34435"]
With the .split() method, you would just need to retrieve the first match:
'2f34435-something.jpg'.split('-')[0];
// "2f34435"
you can use...
/^(.+?)-/gm
which will capture all 3 ( or as many as you have )
You can see it in action here https://regex101.com/r/gD5sU2/2
This will also handle if you get - in the rest of the filename...
such as :-
2f34435-something-else.jpg
4t44234-something.jpg
5465g67-something.jpg
([a-z0-9]+)-[a-z0-9]+.jpg matches each of those strings and the string returned from the first group will match the text before the dash.
Use look ahead for to do it
/^.+?(?=-)/gm
https://regex101.com/r/mW5bO7/2

regex exact match multiple search words using jQuery

I'm using jQuery. I have to check if a given list of words are in a paragraph or not. I want the exact match of a word or a phrase(whole word match).ie, if i search for 'be' in 'Be a bee', only one match is there. I have done like this.
var searchText="tool,media,be,team";
var regexExactMatch = new RegExp('\^' + searchText.split(",").join("|") + '\$');
if (regexExactMatch.test(item.Name))
{
//Found
}
It is working for one search term, ie, without any comma (eg: media).
But for comma separated search, it will break.
How to do a exact match search for multiple search terms. I'm very very new to regex. Also I have to do the same search for integers and date (MM/dd/yyyy). Thanks in advance.
For full input string match use
new RegExp('^(?:' + searchText.split(",").join("|") + ')$');
^^^ ^
For a whole word search, replace ^ and $ with \b:
new RegExp('\\b(?:' + searchText.split(",").join("|") + ')\\b');
Otherwise, the anchors are applied respectively to the first and last alternatives only (i.e. your regex will look like /^tool|media|be|team$/ looking for tool at the beginning only, media and be anywhere in the string and team only at the end of the string).
Note I am using (?:...) non-capturing group since grouping is only necessary here, not capturing (no storing of the submatch). If you need to access the matched text, you can access the 0th group that equals the whole match.
Also, you do not need those \s before ^ and $, they are not necessary at all and are ignored in the constructor notation since there are no escape sequences like \^ and \$.
Remove the ^ from the beginning and $ from the end of the RegExp. Like this :
var regexExactMatch = new RegExp(searchText.split(",").join("|"));
Reason
^ will set the condition that the matched text need to be at the beginning of the string and $ set the condition that the matched text need to be at the end of the string, which can only happen if there is only that text in the string.

Replace multiple spaces, multiple occurrences of a comma

I am trying to clean an input field client side.
Current Value
string = 'word, another word,word,,,,,, another word, ,,;
Desired Value after cleaning
string = 'word,another word,word,another word;
Simplified version of what I have tried http://jsfiddle.net/zg2e7/362/
You can use
var str = 'word,word,word,,,,,new word, , another word';
document.body.innerHTML = str.replace(/(?:\s*,+)+\s*/g, ',');
You need to use g modifier to find and replace all instances
You need to also match optional whitespace between commas and on both sides of them.
Regex explanation:
(?:\s*,+)+ - 1 or more sequences of
\s* - 0 or more whitespace characters
,+ - 1 or more commas.
string = 'word, another word,word,,,,,, another word, ,,';
console.log(string.replace(/(,)[,\s]+|(\s)\s+/g ,'$1').replace(/^,|,$/g,''));
Try using split and trim and map and join rather than regex being that regex can be a bit clunky.
$.map(str.split(','),function(item,i){
if(item.trim()){
return item.trim()
}
}).join(',')
So split the string by the , and then use the map function to combine them. If the item has value after being trimmed then keep the value. Then after it has been mapped to a array of the valid values join them with a comma.

Remove entire word from string if it contains numeric value

What I'm trying to accomplish is to auto-generate tags/keywords for a file upload, basing these keywords from the filename.
I have accomplished auto-generating titles for each upload, as shown here:
But I have now moved on to trying to auto-generate keywords. Similar to titles, but with more formatting. First, I run the string through this to remove commonly used words from the filename (such as this,that,there... etc)
I am happy with it, but I need to not include words that have numbers in it. I have not found a solution on how to remove a word entirely if it contains a number. The solutions I have found like here only works for a certain match, while this one removes numbers alone. I would like to remove the entire word if it contains ANY numeric digit.
To remove all words which contain a number, use:
string = string.replace(/[a-z]*\d+[a-z]*/gi, '');
Try this expression:
var regex = /\b[^\s]*\d[^\s]*\b/g;
Example:
var str = "normal 5digit dig555it digit5 555";
console.log( str.replace(regex,'') );​ //Result-> normal
Apply a simple regular expression to you current filename strings, replacing all occurrences with the empty string. The regular expression matches "words" containing any digits.
Javascript example:
'asdf 8bit jawesome234 mayhem 234'.replace(/\s*\b\w*\d\w*\b/g, '')
Evaluates to:
"asdf mayhem"
Here the regular expression is /\s*\b\w*\d\w*\b/g, which matches maximal sequences consisting of zero or more whitespace characters (\s*) followed by a word-boundary transition (\b), followed by zero or more alphanum characters (\w*), followed by a digit (\d), followed by zero or more alphanum characters, followed by a word-boundary transition (\b). \b matches the empty string at the transition to an alphanumeric character from either the beginning or end of the word or a non-alphanumeric character. The g after the final / of the regular expression means replace all occurrences, not just the first.
Once the digit-words are removed, you can split the string into keywords however you want (by whitespace, for example).
"asdf mayhem".split(/\s+/);
Evaluates to:
["asdf", "mayhem"]
('Apple Cover Photo 23s423 of your 543634 moms').match(/\b([^\d]+)\b/g, '')
returns
Apple Cover Photo , of your , moms
http://jsfiddle.net/awBPX/2/
use this to Remove words containing numeric :
string.replace("[0-9]","");
hope this helps.
Edited :
check this :
var str = 'one 2two three3 fo4ur 5 six';
var result = str.match(/(^[\D]+\s|\s[\D]+\s|\s[\D]+$|^[\D]+$)+/g).join('');

Categories

Resources