JavaScript Regex - add ~ symbol between lettes except letter after space - javascript

how can I put ~ symbol between letters except the first letter after space? Here is what I got from this site by trying here and there.
txt = text.split(/ +?/g).join(" ");
txt.replace(/(.)(?=.)/g, "$1~")
this regex output as
input = "hello friend"
output = "h~e~l~l~o~ ~f~r~i~e~n~d"
How to output "h~e~l~l~o~ f~r~i~e~n~d"?

Use \S instead of . when matching the character you want to insert a ~ next to - \S matches any non-space character, whereas . matches any non-newline character.
const text = 'hello friend';
const singleSpaced = text.split(/ +/g).join(" ");
const output = singleSpaced.replace(/(\S)(?=.)/g, "$1~");
console.log(output);
or
const text = 'hello friend';
const output = text
.replace(/ +/g, ' ')
.replace(/(\S)(?=.)/g, "$1~");
console.log(output);

You can do this in one operation with a replace using this regex:
(?<=\S)(?!$)
It matches the position after a non-whitespace character (?<=\S) except for the position at end of string (?!$). You can then insert a ~ at those positions:
text = "hello friend"
txt = text.replace(/(?<=\S)(?!$)/g, '~')
console.log(txt)

You could match a single non whitespace char, and assert that to the right is not optional whitespace chars followed by the end of the string.
In the replacement use the full match followed by a tilde $&~
\S(?!\s*$)
See a regex demo.
input = "hello friend"
output = input.replace(/\S(?!\s*$)/g, '$&~')
console.log(output)

Related

Replace characters in string with *, but only characters not spaces JavaScript regex

I am wanting to mask some paragraph text out until it is hovered, so if I have a string like,
Hello World
I would want that to be, Hell* ***** how can I replace all characters with with a * after 4 characters/letters?
I know I can do all the string like this,
str.replace(/./g, '*')
but how can I limit it to after the first 4 letters?
var str = "Hello World"
var after4= str.substr(0,4)+str.substr(4).replace(/[^\s]/g, '*')
console.log(after4)
I can do this by Splitting String in Two Parts:
First Part which would remain as it is.
Second Part : I would replace all the Characters by required Character.
Concat both the Strings
let text = 'Hello World';
let str1 = text.substring(0, 4);
let str2 = text.substring(4).replace(/\S/g, '*');
let updatedStr = str1.concat(str2);
console.log(updatedStr);
/*
Single Line
let updatedStr = text.substring(0, 4) + text.substring(4).replace(/\S/g, '*');
*/
Regex Info :
\S : Any other Character other then Space (Capital 'S')
You can combine them in single line Code :
Another option could be capturing the first 4 non whitespace chars using ^(\S{4}) in group 1 and use that in the replacement.
Other non whitespace chars will be matched using an alternation followed by a single non whitspace char |\S, and those matches will be returned as *
^(\S{4})|\S
Regex demo
let str = "Hello World"
.replace(/^(\S{4})|\S/g, (_, g1) => g1 ? g1 : '*');
console.log(str);

Replace Regex Symbols + Blank Space

There is any way to make a regex to replace symbols + blank space?
Im using:
const cleanMask = (value) => {
const output = value.replace(/[_()-]/g, "").trim();
return output;
}
let result = cleanMask('this (contains parens) and_underscore, and-dash')
console.log(result)
Its it right?
Your current code will replace all occurrences of characters _, (, ) and - with an empty string and then trim() whitespace from the beginning and end of the result.
If you want to remove ALL whitespace, you can use the whitespace character class \s instead of trim() like this:
const output = value.replace(/[_()-\s]/g, "");

How to insert space between a number and a character /string using regex in javascript

How to insert space between a number and string / character
I have a regex question.
How do I insert a space between a numeric character and a letter.
For example:
var sentence = "It contains 37mg of salt"
I want the output to be:
It contains 37 mg of salt.
Match a number, lookahead for a letter, then replace with the number with a space after it:
var sentence = "It contains 37mg of salt";
const result = sentence.replace(/\d(?=[a-z])/i, '$& ');
console.log(result);
You can match the number using (\d+) and add a white space in the replaced string in front of the matched number
var sentence = "It contains 37mg of salt"
let res = sentence.replace(/(\d+)/g,"$1 ")
console.log(res)

How can I transfer every line which starts with specific patterns to the end of the string?

I have a string like this:
var str = " this is a [link][1]
[1]: http://example.com
and this is a [good website][2] in my opinion
[2]: http://goodwebsite.com
[3]: http://example.com/fsadf.jpg
[![this is a photo][3]][3]
and there is some text hare ..! ";
Now I want this:
var newstr = "this is a [link][1]
and this is a [good website][2] in my opinion
[![this is a photo][3]][3]
and there is some text hare ..!
[1]: http://example.com
[2]: http://goodwebsite.com
[3]: http://example.com/fsadf.jpg"
How can I do that?
In reality, that variable str is the value of a textarea ... and I'm trying to create a markdown editor .. So what I want is exactly the same with what SO's textarea does.
Here is my try:
/^(\[[0-9]*]:.*$)/g to select [any digit]: in the first of line
And I think I should create a group for that using () and then replace it with \n\n $1
try this:
strLinksArray = str.match(/(\[\d+\]\:\s*[^\s\n]+)/g);
strWithoutLinks = str.replace(/(\[\d+\]\:\s*[^\s\n]+)/g, ''); //removed all links
Here you will get links as array and string without links then do whatever changes you want.
You can use
var re = /^(\[[0-9]*]:)\s*(.*)\r?\n?/gm; // Regex declaration
var str = 'this is a [link][1]\n[1]: http://example.com\nand this is a [good website][2] in my opinion\n[2]: http://goodwebsite.com\n[3]: http://example.com/fsadf.jpg\n[![this is a photo][3]][3]\nand there is some text hare ..!';
var links = []; // Array for the links
var result = str.replace(re, function (m, g1, g2) { // Removing the links
links.push(" " + g1 + " " + g2); // and saving inside callback
return ""; // Removal happens here
});
var to_add = links.join("\n"); // Join the links into a string
document.getElementById("tinput").value = result + "\n\n\n" + to_add; // Display
<textarea id="tinput"></textarea>
See regex demo at regex101.com.
Regex explanation:
^ - start of line (due to the /m modifier)
(\[[0-9]*]:) - Group 1 (referred to as g1 in the replace callback) matching...
\[ - opening square bracket
[0-9]* - zero or more digits
] - closing square bracket
: - a colon
\s* - zero or more whitespace
(.*) - Group 2 matching (g2) zero or more characters other than newline
\r?\n? - one or zero \r followed by one or zero \n
/gm - define global search and replace and ^ matches line start instead of string start

Regular Expression: Any character that is not a letter or number

I need a regular expression that will match any character that is not a letter or a number. Once found I want to replace it with a blank space.
To match anything other than letter or number you could try this:
[^a-zA-Z0-9]
And to replace:
var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');
This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.
\W
For example in JavaScript:
"(,,#,£,() asdf 345345".replace(/\W/g, ' '); // Output: " asdf 345345"
You are looking for:
var yourVar = '1324567890abc§$)%';
yourVar = yourVar.replace(/[^a-zA-Z0-9]/g, ' ');
This replaces all non-alphanumeric characters with a space.
The "g" on the end replaces all occurrences.
Instead of specifying a-z (lowercase) and A-Z (uppercase) you can also use the in-case-sensitive option: /[^a-z0-9]/gi.
This is way way too late, but since there is no accepted answer I'd like to provide what I think is the simplest one: \D - matches all non digit characters.
var x = "123 235-25%";
x.replace(/\D/g, '');
Results in x: "12323525"
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Match letters only /[A-Z]/ig
Match anything not letters /[^A-Z]/ig
Match number only /[0-9]/g or /\d+/g
Match anything not number /[^0-9]/g or /\D+/g
Match anything not number or letter /[^A-Z0-9]/ig
There are other possible patterns
try doing str.replace(/[^\w]/);
It will replace all the non-alphabets and numbers from your string!
Edit 1: str.replace(/[^\w]/g, ' ')
Just for others to see:
someString.replaceAll("([^\\p{L}\\p{N}])", " ");
will remove any non-letter and non-number unicode characters.
Source
To match anything other than letter or number or letter with diacritics like é you could try this:
[^\wÀ-úÀ-ÿ]
And to replace:
var str = 'dfj,dsf7é#lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');
Inspired by the top post with support for diacritics
source
Have you tried str = str.replace(/\W|_/g,''); it will return a string without any character and you can specify if any especial character after the pipe bar | to catch them as well.
var str = "1324567890abc§$)% John Doe #$#'.replace(/\W|_/g, ''); it will return str = 1324567890abcJohnDoe
or look for digits and letters and replace them for empty string (""):
var str = "1324567890abc§$)% John Doe #$#".replace(/\w|_/g, ''); it will return str = '§$)% #$#';
Working with unicode, best for me:
text.replace(/[^\p{L}\p{N}]+/gu, ' ');

Categories

Resources