Related
Let data.title be ABC XYZ PQRS - www.aaa.tld.
Output needs to be like this ABC+XYZ
i've tried this:
var t = data.title.split(' ').join('+');
t = t.replace(/(([^\s]+\s\s*){1})(.*)/,"Unknown");
$("#log").text(t);
Here is one way to do it, no regex though, it only grabs the first two words and must have a space between those words.
First we split into and array, then we slice that array from the 0 index to 2(exclusive) or 1, and finally we join them with a '+':
var x = 'ABC XYZ PQRS';
var y = x.split(' ').slice(0,2).join('+');
// y = "ABC+XYZ"
Working Fiddle
Try using .match() with RegExp /([\w+]+)/g; concatenate first match, + character, second match
var matches = "ABC XYZ PQRS - www.aaa.tld".match(/([\w+]+)/g);
console.log(matches[0] + "+" + matches[1])
This is my general function for first n words. Haven't tested it extensively but it is fast even on long strings because it doesn't use a global regex or split every word. You can fine tune the regex for dealing with punctuation. I'm considering a hyphen as a delimiter but you can move that to the word portion instead if you prefer.
function regFirstWords(s, n) {
// ?: non-capturing subsequent sp+word.Change {} if you want to require n instead of allowing fewer
var a = s.match(new RegExp('[\\w\\.]+' + '(?:[\\s-]*[\\w\\.]+){0,' + (n - 1) + '}'));
return (a === undefined || a === null) ? '' : a[0];
}
To satisfy the OP's request to replace with '+'
regFirstWords('ABC XYZ PQRS - www.aaa.tld',2).replace(/\s/g,'+')
I have this a tag
<a id="Link" href="mysite.net/K&N abc 123.html">Link</a>
I need to use JavaScript to remove non alphanumeric characters then replace spaces with a dash - and lowercase the result.
So everything after /K&N abc 123.html and leave the rest of the href untouched.
The final result would look like this
<a id="Link" href="mysite.com/kn-abc-123.html">Link</a>
I have some code to start but not quite getting it put together right to give the correct result.
var str = document.getElementById("Link").getAttribute("href");
str = str.replace(/\W+/g, '-').toLowerCase();
document.getElementById('Link').setAttribute("href",str);
Here's a bin.
https://jsbin.com/gojoseduji/3/edit?html,output
var href = document.getElementById("Link").getAttribute('href');
var str = href
// replace each block of whitespace with a single '-' character
.replace(/\s+/g, '-')
// Filter out non alphanumerics, excluding : / -
.replace(/[^\:\/\-\w\s.]+/g, "")
// get rid of any hyphens that follow a slash
.replace(/\/-/g, '/')
.toLowerCase();
I just used the whitespace identifier, and make sure to make it global :)
EDIT: Added the condition to strip all non alpha-numerics except [/ - :]. I stripped the whitespace first and had the second regex ignore the hypens. I also made the variable names different, as your original code modified the variable. Just my preference.
EDIT-AGAINN: This original way was nice, but now there's a few different regEx's, maybe someone with smoother regex skills can condense those down and make a better answer?
try this
var str = document.getElementById("Link").getAttribute("href");
var lastitem = str.split("/").pop(); //taking out last item after slash
lastitem = lastitem.split( " " ).map( function(value){ return value.replace(/[*\(\)&/]/g, '').toLowerCase() } ).join( "-" ); //removing special characters and replacing space with hyphen
str = str.substring(0, str.lastIndexOf("/")) + lastitem;
document.getElementById('Link').setAttribute("href",str);
You can use replace with a callback:
var href = document.getElementById("Link").getAttribute('href');
href = href.replace(/^((?:.*?\/{2})?[^\/]*\/)(.+)$/, function($0, $1, $2) {
return $1 + $2.replace(/[^\w\s.]+/g, '').replace(/\s+/g, '-').toLowerCase(); });
document.getElementById('Link').setAttribute("href", href);
//=> mysite.net/kn-abc-123.html
Or with ftp:// in URL:
str = 'ftp://mysite.net/K&N abc 123.html'
str = str.replace(/^((?:.*?\/{2})?[^\/]*\/)(.+)$/, function($0, $1, $2) {
return $1 + $2.replace(/[^\w\s.]+/g, '').replace(/\s+/g, '-').toLowerCase(); });
//=> ftp://mysite.net/kn-abc-123.html
I know the regex that separates two words as following:
input:
'WonderWorld'
output:
'Wonder World'
"WonderWorld".replace(/([A-Z])/g, ' $1');
Now I am looking to remove number in year format from string, what changes should be done in the above code to get:
input
'WonderWorld 2016'
output
'Wonder World'
You can match the location before an uppercase letter (but excluding the beginning of a line) with \B(?=[A-Z]) and match the trailing spaces if any with 4 digits right before the end (\s*\b\d{4}\b). In a callback, check if the match is not empty, and replace accordingly. If a match is empty, we matched the location before an uppercase letter (=> replace with a space) and if not, we matched the year at the end (=> replace with empty string). The four digit chunks are only matched as whole words due to the \b word boundaries around the \d{4}.
var re = /\B(?=[A-Z])|\s*\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match) {
return match ? "" : " ";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
A similar approach, just a different pattern for matching glued words (might turn out more reliable):
var re = /([a-z])(?=[A-Z])|\s*\b\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match, group1) {
return group1 ? group1 + " " : "";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
Here, ([a-z])(?=[A-Z]) matches and captures into Group 1 a lowercase letter that is followed with an uppercase one, and inside the callback, we check if Group 1 matched (with group1 ?). If it matched, we return the group1 + a space. If not, we matched the year at the end, and remove it.
Try this:
"WonderWorld 2016".replace(/([A-Z])|\b[0-9]{4}\b/g, ' $1')
How about this, a single regex to do what you want:
"WonderWorld 2016".replace(/([A-Z][a-z]+)([A-Z].*)\s.*/g, '$1 $2');
"Wonder World"
get everything apart from digits and spaces.
re-code of #Wiktor Stribiżew's solution:
str can be any "WonderWorld 2016" | "OneTwo 1000 ThreeFour" | "Ruby 1999 IamOnline"
str.replace(/([a-z])(?=[A-Z])|\s*\d{4}\b/g, function(m, g) {
return g ? g + " " : "";
});
import re
remove_year_regex = re.compile(r"[0-9]{4}")
Test regex expression here
Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code.
I got a working fiddle. But it has a bug.
var str = 'This, is a test.';
alert( removeLastComma(str) ); // should remain unchanged
var str = 'This, is a test,';
alert( removeLastComma(str) ); // should remove the last comma
var str = 'This is a test, ';
alert( removeLastComma(str) ); // should remove the last comma
function removeLastComma(strng){
var n=strng.lastIndexOf(",");
var a=strng.substring(0,n)
return a;
}
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
The / mark the beginning and end of the regular expression
The , matches the comma
The \s means whitespace characters (space, tab, etc) and the * means 0 or more
The $ at the end signifies the end of the string
you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Here is an Example
function myFunction() {
var strVal = $.trim($('.txtValue').text());
var lastChar = strVal.slice(-1);
if (lastChar == ',') { // check last character is string
strVal = strVal.slice(0, -1); // trim last character
$("#demo").text(strVal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="txtValue">Striing with Commma,</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
function removeLastComma(str) {
return str.replace(/,(\s+)?$/, '');
}
In case its useful or a better way:
str = str.replace(/(\s*,?\s*)*$/, "");
It will replace all following combination end of the string:
1. ,<no space>
2. ,<spaces>
3. , , , , ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:
let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '
https://jsfiddle.net/dc8moa3k/
long shot here
var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true) {
currentIndex=pattern.lastIndex;
}
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
alert(sentence);
Remove last comma. Working example
function truncateText() {
var str= document.getElementById('input').value;
str = str.replace(/,\s*$/, "");
console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>
First, one should check if the last character is a comma.
If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
str = str.substring(0, str.length - 1);
}
NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)
you can remove last comma:
var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);
To remove the last comma from a string, you need
text.replace(/,(?=[^,]*$)/, '')
text.replace(/,(?![^,]*,)/, '')
See the regex demo. Details:
,(?=[^,]*$) - a comma that is immediately followed with any zero or more chars other than a comma till end of string.
,(?![^,]*,) - a comma that is not immediately followed with any zero or more chars other than a comma and then another comma.
See the JavaScript demo:
const text = '1,This is a test, and this is another, ...';
console.log(text.replace(/,(?=[^,]*$)/, ''));
console.log(text.replace(/,(?![^,]*,)/, ''));
Remove whitespace and comma at the end use this,
var str = "Hello TecAdmin, ";
str = str.trim().replace(/,(?![^,]*,)/, '')
// Output
"Hello TecAdmin"
The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.
EDIT: Is it really that confusing?
'This, is a random string'
Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.
With or without Regex.
I suggest two processes and also consider removing space as well. Today I got this problem and I fixed this by writing the below code.
I hope this code will help others.
//With the help of Regex
var str = " I am in Pakistan, I am in India, I am in Japan, ";
var newstr = str.replace(/[, ]+$/, "").trim();
console.log(newstr);
//Without Regex
function removeSpaceAndLastComa(str) {
var newstr = str.trim();
var tabId = newstr.split(",");
strAry = [];
tabId.forEach(function(i, e) {
if (i != "") {
strAry.push(i);
}
})
console.log(strAry.join(","));
}
removeSpaceAndLastComa(str);
If you are targeting es6, then you can simply do this
str = Array.from( str ).splice(0, str.length - 1).join('');
This Array.from(str) converts the string to an array (so we can slice it)
This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the array
This join('') joins the entries in the array to form a string
Then if you want to make sure that a comma actually ends the string before performing the operation, you can do something like this
str = str.endsWith(',') ? Array.from(str).splice(0,str.length - 1).join('') : str;
$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}