I'm rather new to jQuery / JS and wondering how to do the following:
Big Sofa - Pink
Big Sofa - Blue
Small Sofa - Red
Small Sofa - Grey
What I need to do is remove all the text before and including the "-" so it just shows the colour, need to wildcard it so will get anything and replace with nothing.
Is this possible?
I would recommend using regex.
Here's example when you're using span for each entry:
$(document).ready(function() {
$("span").each(function() {
var text = $(this).text();
text = text.replace(/(\w+\s)+-\s/g, "");
$(this).text(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Sofa test - red</span>
<span>Table test - blue</span>
try this simple one
var a = "Big Sofa - Pink\nBig Sofa - Blue\nSmall Sofa - Red\nSmall Sofa - Grey"
var newA = a.split( "\n" ).map( function(value){ return value.split( "-" ).pop() } ).join( "\n" );
console.log( newA );
This regular expression will work on multiline strings:
var str = 'Big Sofa - Pink\nBig Sofa - Blue\nSmall Sofa - Red\nSmall Sofa - Grey';
str.replace(/.+\-\s*/g, '').split(/\n/);
You can do it as
var text = "Big Sofa - Pink";
var color = text.substring(text.indexOf("-") + 1)
Your best bet is to use regular expressions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
var text = 'Big Sofa - Pink';
var color = text.replace(/^.+?- (\w+)$/i, '$1'); // Pink
^ matches the start of the string
. matches any character, including white space
+ indicates that the preceding matcher have to occur 1 or more times
? after a multiplier indicates that the matching is non greedy (matches the minimum possible)
- matches literally a dash and a space
(\w+) matches any word composed by 1 or more word characters (letters, numbers and underscore) and capture its value in a group (group 1 in this case)
$ matches the end of the string
i (at the end) indicates that the match is case insensitive
The replace string ($1) replaces the entire match by the content of the capture group 1. In our case it matches the color.
Related
I need to select some text between % signs where there is not white space between 2 %.
This should match:
%link%
This shouldn't:
%my link%
This easy regex would do the trick:
/%\S*%/g
But there is a catch: I can add a prefix: % and a suffix: % but the regex must contain this between these: (.+?)
(it's a third party script).
So this is the regex I need to adjust:
/%(.+?)%/
Because of "(.+?)" I need a workaround, any idea?
UPDATE:
All of these are true for a perfect regex:
regex = /%(.+?)%/g // default regex which allows spaces so it's not good
regex.test('%link%')
regex.test('%my link%') === false
regex.toString().includes('(.+?)')
You can use
var some_hardcoded_value = ".+?";
var regex = new RegExp("%(?=[^\\s%]+%)" + some_hardcoded_value + "%", "g");
See the regex demo.
Details:
% - a % char
(?=[^\s%]+%) - a positive lookahead that requires any one or more chars other than whitespace and % immediately to the right of the current location
(.+?) - Group 1: any one or more chars other than line break chars
% - a% char.
See a JavaScript demo:
const some_hardcoded_value = ".+?";
const regex = new RegExp("%(?=[^\\s%]+%)(" + some_hardcoded_value + ")%", "g");
const str = "%link% This shouldn't %my link% %%link,,,,,%%%%";
console.log(Array.from(str.matchAll(regex), x => x[1]));
I have problem with simple rexex. I have example strings like:
Something1\sth2\n649 sth\n670 sth x
Sth1\n\something2\n42 036 sth\n42 896 sth y
I want to extract these numbers from strings. So From first example I need two groups: 649 and 670. From second example: 42 036 and 42 896. Then I will remove space.
Currently I have something like this:
\d+ ?\d+
But it is not a good solution.
You can use
\n\d+(?: \d+)?
\n - Match new line
\d+ - Match digit from 0 to 9 one or more time
(?: \d+)? - Match space followed by digit one or more time. ( ? makes it optional )
let strs = ["Something1\sth2\n649 sth\n670 sth x","Sth1\n\something2\n42 036 sth\n42 896 sth y"]
let extractNumbers = str => {
return str.match(/\n\d+(?: \d+)?/g).map(m => m.replace(/\s+/g,''))
}
strs.forEach(str=> console.log(extractNumbers(str)))
If you need to remove the spaces. Then the easiest way for you to do this would be to remove the spaces and then scrape the numbers using 2 different regex.
str.replace(/\s+/, '').match(/\\n(\d+)/g)
First you remove spaces using the \s token with a + quantifier using replace.
Then you capture the numbers using \\n(\d+).
The first part of the regex helps us make sure we are not capturing numbers that are not following a new line, using \ to escape the \ from \n.
The second part (\d+) is the actual match group.
var str1 = "Something1\sth2\n649 sth\n670 sth x";
var str2 = "Sth1\n\something2\n42 036 sth\n42 896 sth y";
var reg = /(?<=\n)(\d+)(?: (\d+))?/g;
var d;
while(d = reg.exec(str1)){
console.log(d[2] ? d[1]+d[2] : d[1]);
}
console.log("****************************");
while(d = reg.exec(str2)){
console.log(d[2] ? d[1]+d[2] : d[1]);
}
I have this function that finds whole words and should replace them. It identifies spaces but should not replace them, ie, not capture them.
function asd (sentence, word) {
str = sentence.replace(new RegExp('(?:^|\\s)' + word + '(?:$|\\s)'), "*****");
return str;
};
Then I have the following strings:
var sentence = "ich mag Äpfel";
var word = "Äpfel";
The result should be something like:
"ich mag *****"
and NOT:
"ich mag*****"
I'm getting the latter.
How can I make it so that it identifies the space but ignores it when replacing the word?
At first this may seem like a duplicate but I did not find an answer to this question, that's why I'm asking it.
Thank you
You should put back the matched whitespaces by using a capturing group (rather than a non-capturing one) with a replacement backreference in the replacement pattern, and you may also leverage a lookahead for the right whitespace boundary, which is handy in case of consecutive matches:
function asd (sentence, word) {
str = sentence.replace(new RegExp('(^|\\s)' + word + '(?=$|\\s)'), "$1*****");
return str;
};
var sentence = "ich mag Äpfel";
var word = "Äpfel";
console.log(asd(sentence, word));
See the regex demo.
Details
(^|\s) - Group 1 (later referred to with the help of a $1 placeholder in the replacement pattern): a capturing group that matches either start of string or a whitespace
Äpfel - a search word
(?=$|\s) - a positive lookahead that requires the end of string or whitespace immediately to the right of the current location.
NOTE: If the word can contain special regex metacharacters, escape them:
function asd (sentence, word) {
str = sentence.replace(new RegExp('(^|\\s)' + word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '(?=$|\\s)'), "$1*****");
return str;
};
I Want to replace spaces in a string in javascript. But only if there is a price behind it.
Example:
var before = 'Porto Rood / Wit 4,00';
var after = 'Porto Rood / Wit;4,00';
The regex I use is \s\d+,\d{2}
In javascript is there a way to replace only the first character of a regex match ?
You can use positive lookahead to match only the whitespace before the price.
var before = 'Porto Rood / Wit 4,00',
after = before.replace(/\s(?=\d+,\d{2})/, ';');
console.log(after);
I have a var that contains a big list of words (millions) in this format:
var words = "
car
house
home
computer
go
went
";
I want to make a function that will replace the newline between each word with space.
So the results would something look like this:
car house home computer go went
You can use the .replace() function:
words = words.replace(/\n/g, " ");
Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.
Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.
let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");
console.log("After:");
console.log(words);
In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use
var new_words = words.replace(/[\r\n]+/g," ");
See regex demo
To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:
[ - start of a positive character class matching any single char defined inside it:
\r - (\x0D) - \n] - a carriage return (CR)
\n - (\x0A) - a line feed character (LF)
\x0B - a line tabulation (LT)
\x0C - form feed (FF)
\u0085 - next line (NEL)
\u2028 - line separator (LS)
\u2029 - paragraph separator (PS)
] - end of the character class
+ - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
/g - find and replace all occurrences in the provided string.
var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Some simple solution would look like
words.replace(/(\n)/g," ");
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')
const words = `He had
concluded that pigs
must be able
to fly in Hog Heaven.
`
document.body.innerHTML = "<pre>without-Trim-And-Remove:\n" + words + "</pre>";
trimAndRemoveSymbols=(text)=>{
return text.replace(/[\n]+/g, '').trim();
}
document.body.innerHTML += "<pre>Trim-And-Remove:\n" + trimAndRemoveSymbols(words) + "</pre>";