Regex: find capitalized words [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How do I find and extract capitalized words of a string with regex?
I would like to:
extract the capitalized words of a string, as an array
extract the last capitalized word of a string, as a substring:
Both with one regex
If I have this:
var str="This is a STRING of WORDS to search";
I would like to get this 1:
allCapWords // = ["STRING", "WORDS"]
and 2:
lastCapWord // = "WORDS"

To extract the words into an array:
var allCapWords = str.match(/\b[A-Z]+\b/g);
-> ["STRING", "WORDS"]
(Here's a Regex101 test with your string.)
To pull the last word:
var lastCapWord = allCapWords[allCapWords.length - 1];
-> "WORDS"

var str="This is a STRING of WORDS to search";
var regObj = /\b([A-Z]+)\b/g;
allCapWords = str.match(regObj);

You can try this regexpr /\b[A-Z]+\b/gor \b[A-Z0-9]+\b/g if you are interested in catch numbers inside the string

Related

regex match first occurrence of a single character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'll make this extremely simple
I have a function that comes across a string as such by design: water 'thing one'
I need to split this string by the first space, since there are spaces elsewhere.
I've tried many regex expressions like / .*? /, but they can only match two consecutive spaces.
How do I do this?
Thanks in advance.
If you just want the portion of the string before and after the first space, you could use regex replacement here:
var input = "water 'thing one'";
var first = input.replace(/[ ].*$/, "");
var second = input.replace(/^\S*[ ]/, "");
console.log("first part: " + first);
console.log("second part: " + second);
You can capture them using String#match with this regex:
/(.*?) (.*)/
const text = "water 'thing one'";
const [, first, second] = text.match(/(.*?) (.*)/);
console.log('first:', first);
console.log('second:', second);

Find and replace # mentions using Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to parse strings to find and replace # mentions.
Here is a sample string:
Hi #jordan123 and #jordan have a good day
I want to find and replace #jordan with #jordananderson without modifying #jordan123
I used this regex to find a list of all of the mentions in the string:
let string = 'Hi #jordan123 and #jordan have a good day'
let result = string.match(/\B\#\w\w+\b/g);
that returns:
['#jordan123', '#jordan']
But I can't figure out how to continue and complete the replacement.
Valid characters for the username are alphanumeric and always start with the # symbol.
So it also needs to work for strings like this:
Hi #jordan123 and #jordan!! have a good day
And this
Hi #jordan123! and !#jordan/|:!! have a good day
My goal is to write a function like this:
replaceUsername(string, oldUsername, newUsername)
If I understand your question correctly, you need \b, which matches a word boundary:
The regex: #jordan\b will match:
Hi #jordan123 and #jordan!! have a good day
Hi #jordan123! and !#jordan/|:!! have a good day
To build this regex, just build it like a string; don't forget to sanitize the input if it's from the user.
var reg = new RegExp("#" + toReplace + "\\b")
In general if you have one string of a found value, and a larger string with many values, including the found value, you can use methods such as split, replace, indexOf and substring etc to replace it
The problem here is how to replace only the string that doesn't have other things after it
To do this we can first look for indexOf the intended search string, add the length of the string, then check if the character after it doesn't match a certain set of characters, in which case we set the original string to the substring of the original up until the intended index, then plus the new string, then plus the substring of the original string starting from the length of the search string, to the end. And if the character after the search string DOES match the standard set of characters, do nothing
So let's try to make a function that does that
function replaceSpecial(original, search, other, charList) {
var index= original.indexOf(search)
if(index > -1) {
var charAfter = original [index + search.length]
if (!charList.includes(charAfter)) {
return original. substring (0, index) + other + original. substring (index+ search.length)
} else return original
} else return original
}
Then to use it with our example
var main ="Hi #jordan123 and #jordan!! have a good day"
var replaced = replaceSpecial (main, "#jordan", "#JordanAnderson", [0,1,2,3,4,5,6,7,8,9])

Split a string using a regex [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like to split the following str into an array that has 2 elements, the first being 'Some words in a sentence', the second being 'ABC' where ABC can be any upper case character.
const str = 'Some words in a sentence (ABC)';
const regex = ?
const arr = str.split(regex);
...
expect(arr[0]).to.eq('Some words in a sentence');
expect(arr[1]).to.eq('ABC');
expect(arr.length).to.eq(2);
Any thoughts would be appreciated.
Cheers,
Paul
The trick with regex is to break it into steps.
You want two elements, that means two groups, e.g. (<-- between these -->))
The easy one is getting the (ABC) at the end -> \((.*?)\)$ (escaped ()'s
And now you can conclude the rest is the other part: (.*?)
Explained:
/---\ is the \((.*?)\)$
Some words in a sentence (ABC)
^---- (.*?) ----^
That should push you in the direction you are looking for, the final part is for you to figure out :)
Goto https://regex101.com/ and try this
/(.*)\(([A-Z]{3})\)/
with your string
'Some words in a sentence (ABC)'
You will get
Match 1
Full match 0-30 `Some words in a sentence (ABC)`
Group 1. 0-25 `Some words in a sentence `
Group 2. 26-29 `ABC`

Replace an expression in string using javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a string that has some numbers in the middle of the string.
For example,
var str = "abcd-123456.com"
I want to remove the numbers like this
abcd.com
I am not trying to replace all numbers.
I have to replace only -*. expression with "".
How do I do this in JavaScript?
var str = "abcd-123456.com"
str = str.replace(/-[0-9]*/g, '')
Your comments lead me to believe you want
var str = "abcd-123456.com";
var str1 = str.substring(0,str.indexOf("-"))+str.substring(str.indexOf("."))
console.log(str1);
//or with regex
// dasah plus 6 digits to nothing
var str2 = str.replace(/-\d{6}/,"")
console.log(str2);
// dash, digits and an dot to dot
var str3 = str.replace(/-\d+\./,".")
console.log(str3);
AS PER YOUR COMMENT
The answer of Shivaji Varma will nearly do the tricks.
var str = "abc5d-123456.c0om"
str = str.replace(/-[0-9]*./g, "")
console.log(str)
Soooo,
Using the slash indicate a regular expression.
[0-9] indicate you want to replace all digit between 0 and 9 (included)
"*" to remove all digits
"-" and "." to delimite

Get part of the string using regexp [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've a strings, which can have a text like:
'some text user#t12# some text'
'username#John# some text'
'some text usersurname#Malks#'
'userphoto#1.jpg#'
How do I get a text between # and # symbols?
There's a typical structure of the part of the string to search for - type#variable#
type is a JS variable type, it's placed before the first #.
variable is a text that I need to get.
I'm searching for a regexp, that return variable, that is between #...#.
The problem is, I'm not too familiar with regexp, can you help me please?
You need to use capture groups, basically in a regex anything in brackets will be part of the cpature group, in this case you want to capture all the characters between two hashes. The any amount of characters regex is .* so this is what you want to capture between two hashes. Once you execute it you will find the match as second in the array (the first will be the string with the hashes.
var type = "";
var myString = "some text user#t12# some text";
var myRegexp = new RegExp(type+"#(.*)#","g");
var match = myRegexp.exec(myString);
alert(match[1]); // t12
any other matches between hashes will be in match[2].. match[n]

Categories