'Javascript get complete word after matching special character in string
This code not running when put Textx-yz but runs fine when put Textx-y
I want a alert(Textx-yz) when put Textx-,Textx,Textx-yz in match
alert('Textabc Textx-yz TextTypeTestingText'.match(/Textx-yz\S+/)[0])
Solution 1:[1]
you can use word boundaries and exact match to get this match:
\b(Textx\-yz)+\b
\b - searches whole words only
and in between we tell it what we want to find
Solution 2:[2]
If I understand what you mean you can this pattern:
'Textabc Textx-yz TextTypeTestingText'.match(/Textx-yz \S+/)[0]
Actually I add a space after -yz in match method
Solution 3:[3]
If you need the expression to match in any given string the pattern Textx followed or not by a dash and [a-ZA-Z0-9_] characters, the regex you are looking for is: (Textx(-[\w]+)?)
It's not perfectly clear what did you expect when the string contained an invalid expression like 'Textx- unwanted'. In this case my code returns 'Textx' with no following dash. Anyway I separated the capture group for the second part so that you could add further logic in the doMatch function doing some further consideration beyond the regex.
Here's a demo:
function doMatch(subject){
//this is an expression having 1 optional grouped capture as being the part "dash following something"
let pattern = /Textx(-[\w]+)?/;
let match = subject.match(pattern);
//the whole text matched by the expression
//console.log(match[0]);
//the optional text matched after Textx starting with dash and at least one \w char
//this will be undefined if 'Textx-' or 'Textx' but not for 'Textx-anything'
//console.log(match[1]);
return match[0];
}
console.log('------begin------');
let matchedString;
//1- Textx (alone)
matchedString = doMatch('Textx');
console.log( matchedString ); //-> Textx
//2- Textx (alone and having further text later separated by space)
matchedString = doMatch('Textabc Textx unwanted');
console.log( matchedString ); //-> Textx
//3- Textx (followed by '-randomstuff')
matchedString = doMatch('Textabc Textx-randomstuff');
console.log( matchedString ); //-> Textx-randomstuff
//4- Textx (followed by '-randomstuff' and having further text later separated by space)
matchedString = doMatch('Textabc Textx-randomstuff unwanted');
console.log( matchedString ); //-> Textx-randomstuff
//5- Textx- (where the dash is not followed by valid characters and it's the end of string)
matchedString = doMatch('Textx-');
console.log( matchedString ); //-> Textx
//6- Textx- (where the dash is not followed by valid characters and there's further text)
matchedString = doMatch('Textabc Textx- unwanted');
console.log( matchedString ); //-> Textx
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guy Nachshon |
| Solution 2 | masoud |
| Solution 3 | Diego De Vita |
