Separating Id from string by using regex - javascript

how can I get the first part of ID from the following string?
sText ='DefId #AnyId #MyId';
sText = sText.replace(/ #.*$/g, '');
alert(sText);
The result should be as follows: "DefId #AnyId "
Many thanks in advance.

var sText ='DefId #AnyId #MyId';
var matches = sText.match(/(DefId #.*) #.*/);
if(matches && matches.length > 0) {
alert(matches[1]);
}
Move the grouping parenthesis right 1 character if you also want the space after the first ID. This assumes that the IDs won't contain a #.

You could use this regex,
(.*)#.*?$
DEMO
JS code,
> var sText ='DefId #AnyId #MyId';
undefined
> sText = sText.replace(/(.*)#.*?$/g, '$1');
'DefId #AnyId '
If you don't want any space after #AnyId, then run the below regex to remove that space.
> sText = sText.replace(/(.*) #.*?$/g, '$1');
'DefId #AnyId'

If you need to get rig of everything after last # in the string, use:
sText.replace(/#[^#]+$/, '');

Related

javascript replace all

I have a sting like:
var tmp='Hello
I am
( Peter';
I want to replace all words with this pattern &...; to '';
How I can change the code below to make it work:
tmp=String(tmp).replace(/
/g, "");
Thank you.
Update regex with \d{2} instead of the 10 to match any two digit numbers.
var tmp = 'Hello
I am
( Peter';
tmp = String(tmp).replace(/&#\d{2};/g, "");
console.log(tmp);
try this /&#(\d+)(;)/g .Its match the numbers upto reach of ; end
Normal Regex
var tmp='Hello
I am
( Peter';
console.log(tmp.replace(/&#(\d+)(;)/g,""))
Remove the Empty space also use: /(\s+)&#(\d+)(;)/g .\s+ match the empty space before the pattern
Empty space match
var tmp='Hello
I am
( Peter';
console.log(tmp.replace(/(\s+)&#(\d+)(;)/g,""))

Remove whitespace after a particular symbol

I've got a string which has the > symbol multiple times. After every > symbol there is a line break. How can I remove whitespaces after every > symbol in the string?
This is what I tried for spaces. But I need to remove whitespaces only after > symbol.
str.replace(/\s/g, '');
String:
<Apple is red>
<Grapes - Purple>
<Strawberries are Red>
If you are trying to remove newline characters you can use RegExp /(>)(\n)/g to replace second capture group (\n) with replacement empty string ""
var str = `<Apple is red>
<Grapes - Purple>
<Strawberries are Red>`;
console.log(`str:${str}`);
var res = str.replace(/(>)(\n)/g, "$1");
console.log(`res:${res}`);
Try this:
str.replace(/>\s/g, '>')
Demo:
console.log(`<Apple is red>
<Grapes - Purple>
<Strawberries are Red>`.replace(/>\s/g, '>'))
Use the following approach:
var str = 'some> text > the end>',
replaced = str.replace(/(\>)\s+/g, "$1");
console.log(replaced);
You must use /m flag on your regex pattern
You must use $1 capture group symbol on your replacement text
var text = '<Apple is red>\r\n<Grapes - Purple>\r\n<Strawberries are Red>';
var regex = /(>)\s*[\n]/gm;
var strippedText = text.replace(regex,'$1');

Remove dot . sign from the end of the string

I have this requirement where it is required to remove only the last . dot sign from a string.
Say if we have var str = 'abcd dhfjd.fhfjd.'; i need remove the final dot sign which would output abcd dhfjd.fhfjd .
I found this link ( Javascript function to remove leading dot ) which removes the first dot sign but I am new to this whole thing and could not find any source on how to remove a specific last character if exists.
Thank you :)
Single dot:
if (str[str.length-1] === ".")
str = str.slice(0,-1);
Multiple dots:
while (str[str.length-1] === ".")
str = str.slice(0,-1);
Single dot, regex:
str = str.replace(/\.$/, "");
Multiple dots, regex:
str = str.replace(/\.+$/, "");
if(str.lastIndexOf('.') === (str.length - 1)){
str = str.substring(0, str.length - 1);
}
This will remove all trailing dots, and may be easier to understand for a beginner (compared to the other answers):
while(str.charAt(str.length-1) == '.')
{
str = str.substr(0, str.length-1);
}

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

What is the correct pattern for splitting a string in javascript, leaving just a-z words

I have the next code that was given to me to split up a string into an array.
var chk = str.split(/[^a-z']+/i);
The problem I'm having with this solution is that if the string has a period in the end, it's being replaced with ","
For example:
If I have the next string: "hi,all-I'm-glad."
The solution above results: "hi,all,I'm,glad," (notice the "," in the end).
I need that the new string will be: "hi,all,I'm,glad"
How can I acheive it ?
Check for a . being the last character and remove it first
var str = "hi,all-I'm-glad. that you, can help,me. that-doesn't make any-sense, I know.";
if(str.charAt( str.length-1 ) == ".") {
str = str.substring(0,str.length-1);
}
var chk = str.split(/[^a-z']+/i);
console.log(chk);
var chk = str.match(/[a-z']+/gi);
console.log(chk);
You could check to see if the last element of your string array returns an empty string and remove that element
if (chk[chk.length-1] == "")
{
chk.pop();
}
var chk="to.to.".split(/[^a-z']+/i); if(chk[chk.length-1].length==0){chk.pop()}; console.log(chk);
To remove the last value of your array using pop if this one is empty.
You can utilize the pure regex power:
"hi,all-I'm-glad. that you, can help,me. that-doesn't make any-sense, I know.".replace(/[\-\.\s]/g, ',').replace(/,{2,}/g, ',').replace(/,$/,'')

Categories

Resources