我有一个输出地址的变量,例如:Budapest, Mindegy utca, 1002 Hungary
。我不需要数字和'Hungary
',只有第一部分。在逗号后加上任意数字后分割一个字符串
所以我想分割,如果有逗号后跟任意数字。
地址的输出上面应该是:Budapest, Mindegy utca
这就是我试图做的:
addressVariable.split(', /\[[0-9]+\]/');
但它不会拆分变量。
我有一个输出地址的变量,例如:Budapest, Mindegy utca, 1002 Hungary
。我不需要数字和'Hungary
',只有第一部分。在逗号后加上任意数字后分割一个字符串
所以我想分割,如果有逗号后跟任意数字。
地址的输出上面应该是:Budapest, Mindegy utca
这就是我试图做的:
addressVariable.split(', /\[[0-9]+\]/');
但它不会拆分变量。
使用String.prototype.replace
删除不需要的部分:
'Budapest, Mindegy utca, 1002 Hungary'.replace(/,\s*\d+.*/, '')
// => "Budapest, Mindegy utca"
谢谢,按预期工作! :) – PeterInvincible
@TrisztánThar,不客气。很高兴帮助你解决问题。 – falsetru
只是分裂根据该inturn后跟零个或多个空格和数字,atlast打印索引0拿到的第一个值逗号输入。
> "Budapest, Mindegy utca, 1002 Hungary".split(/,(?=\s*\d+)/)[0]
'Budapest, Mindegy utca'
OR
你可以使用string.match
功能。
> "Budapest, Mindegy utca, 1002 Hungary".match(/^.*?(?=,\s*\d+)/)[0]
'Budapest, Mindegy utca'
到逗号后跟任意数量的分割后的字符串在javascript使用:
result = text.split(/,(?=\s*\d)/);
顺便说一句,' '/ \ [[0-9] + \] /''是不一个有效的正则表达式对象,它是一个简单的字符串。 – DontVoteMeDown