How to regex, and add "-" between words? - javascript

UPDATED
I been looking around in the old interweb to see if there is any way I can regex this as part of a replace method I'm doing: str.replace(/\w[A-Z]/gm, "-")
thisIsARegex
into this:
this-Is-A-Regex
I tried to mess around on regex101 with matching a \w character followed by [A-Z] but failed.
Any thoughts?

If the first char can't be uppercase:
var str = "thisIsARegex";
str = str.replace(/(?=[A-Z])/g, "-");
console.log(str); // this-Is-A-Regex
If the first char can be uppercase:
var str = "ThisIsARegex";
str = str.replace(/.(?=[A-Z])/g, "$&-");
console.log(str); // This-Is-A-Regex
or
var str = "ThisIsARegex";
str = str.replace(/\B(?=[A-Z])/g, "-");
console.log(str); // This-Is-A-Regex
(Last snippet suggested by #Thomas.)

var s = "thisIsARegex";
s = s.replace(/([A-Z])/g, '-$1').trim();
console.log(s);

Try this one:
you can check regex on this page and make your own tests:
https://regexr.com/
// initial value
let text = "thisIsARegexText";
// select Uppercase characters
let regexPattern = /[^a-z]/g;
// dump temp array
let newText = [];
// go through all characters, find Uppercase and replace with "-UppercaseCharacter"
for(i of text){
newText.push(i.replace(/[^a-z]/g, "-" + i))
}
// assign the result to the initial variable
text = newText.join("");

Related

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

add hyphen after every fourth character in a string seperated by comma

I have a string as 1111111111,2222222222,333333333,....
I want to modify it as 1111-111111,2222-222222,3333-33333,....
the regex I am using is this..
var num = '1111111111,2222222222,333333333,....';
var newNum = num.toString().match(/.{4}/g).join('-');
this add hyphen after every fourth character but I am unable to reset when comma is found.
You can use the following regex:
\b\d{4}
with replacement $&-
demo
var num = '1111111111,2222222222,333333333,....';
console.log(num.replace(/\b\d{4}/g, "$&-"));
Try following
let str = '1111111111,2222222222,333333333';
let res = str.split(",").map(s => s.slice(0,4) + "-" + s.slice(4, s.length-1)).join(",");
console.log(res);
You can also use split() and substr() to get that:
var str = '1111111111,2222222222,333333333';
var res =[];
str.split(',').forEach((item)=>{
res.push(item.substr(0,4)+'-'+item.substr(4,item.length));
});
console.log(res);

Replacing words in text that match regex

I am trying to replace all words in my text that match a give regex. I have made a function that looks like this:
const str = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
let newStr;
if (str.match(regex)) {
for(let i = 0; i < str.match(regex).length; i++) {
let url = str.match(regex)[i] + ' target="_blank"';
newStr = str.replace(str.match(regex)[i], url);
}
}
But, this is not right, since only the last value of the matching string will be replaced in the newStr, since in the loop is always taking the text from the str variable, how can I make it so that I loop through updated newStr, and replace all the values that match regex?
This works fine
Look at String.prototype.replace definition
const str = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
let newStr = str.replace(/(href=\')([^\']*)(\')/g, '$& target="_blank"')

How I can replace a underscore with an space inside a word starting with an special char in javascript?

I have this string:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
And I'm trying to replace the ALL the underscores with spaces for any word starting with exclamation sing (!) so the string should looks like this one:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap Accessible},currentView:!map}";
I spent a few hours trying to figure out how to do that without success.
Try to use function replacement form (example):
str.replace(/!\w+/g, function(x) { return x.replace(/_/g, ' '); })
Regexp /!\w+/g selects all words started with "!". After that we replace each word x with result of x.replace(/_/g, ' ').
You can use the regex
!([^_]+)_([^]+)
and replace with $1 $2
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
console.log(str.replace(/!([^_]+)_([^]+)/g, "!$1 $2"));
(![^_]+)_([a-zA-Z0-9]+)
Try this.See demo.
http://regex101.com/r/tF5fT5/57
var re = /(![^_]+)_([a-zA-Z0-9]+)/gm;
var str = '{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}';
var subst = '$1 $2';
var result = str.replace(re, subst);

Remove a letter(:) from a string

I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim() to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim() method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
You can replace all : characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim() function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace or substr methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
To chop the last character of a string use string.slice(0,-1)
You can use a regular expression to remove the colon (:).
Replace one instance:
var with_colon = 'Stuff:';
var regex = /([^:]*):/;
var without_colon = regex.exec(with_colon)[1];
alert(without_colon);
Result: Stuff
Replace all instances:
var with_colon = 'Stuff: Things:';
var without_colon = with_colon.replace(/([^:]*):/g,'$1');
alert(without_colon);
Result: Stuff Things
var myStr = "something:";
myStr = myStr.slice(0, -1);
var a="name:";
var b=a.split(":");
alert(b[0]);
one way is to use lastIndexOf
var str='Name:, Call:, Phone:';
var index=str.lastIndexOf(":");
alert(index);
var s=str.substring(0,index);
alert(s);
DEMO
This checks if the last character is a colon. If it is, the last character is removed.
if (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
If there can be multiple trailing colons, you can replace if with while, like this:
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
You could even make a generic trim function that accepts a string and a character and trims trailing instances of that character:
var trim = function(str, chr) {
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
return str;
}
function trim(str) {
str = str.replace(/^:*/,"");
return str.replace(/:*$/,"");
}
str = str.substring(0,str.lastIndexOf(":"));
Note that this removes everything from the last : to the end of the string (for example, any whitespace after the :).

Categories

Resources